循环遍历包含 10 个 url 的 python 数据框并从中提取内容 (BeautifulSoup)

Loop through a python dataframe with 10 urls and extract contents from them (BeautifulSoup)

我有一个名为 'df' 的包含 1 列的 csv。我有一个 header 和 10 个网址。

Col
"http://www.cnn.com"
"http://www.fark.com"
etc 
etc

这是我的错误代码

import bs4 as bs
df_link = pd.read_csv('df.csv')    
for link in df_link:
        x = urllib2.urlopen(link[0])
        new = x.read()
# Code does not even get past here as far as I checked
        soup = bs.BeautifulSoup(new,"lxml")
        for text in soup.find_all('a',href = True):
            text.append((text.get('href')))

我收到一条错误消息

ValueError: unknown url type: C

我还收到此错误的其他变体,例如

问题是,它甚至都没有过去

x = urllib2.urlopen(link[0])

另一方面;这是工作代码...

url = "http://www.cnn.com"
x = urllib2.urlopen(url)
new = x.read()
soup = bs.BeautifulSoup(new,"lxml")
for link in soup.find_all('a',href = True):
    links.append((link.get('href')))

固定答案

我不知道你在使用 pandas,所以我说的不是很有帮助。

您想要使用 pandas 执行此操作的方法是遍历行并从中提取信息。以下应该工作而不必摆脱 header:

import bs4 as bs
import pandas as pd
import urllib2

df_link = pd.read_csv('df.csv')

for link in df_link.iterrows():
    url = link[1]['Col']
    x = urllib2.urlopen(url)
    new = x.read()
    # Code does not even get past here as far as I checked
    soup = bs.BeautifulSoup(new,"lxml")
    for text in soup.find_all('a',href = True):
        text.append((text.get('href')))

下面是误导性的原始答案

您的 CSV 文件的 header 似乎没有被单独处理,因此在 df_link 的第一次迭代中,link[0]"Col",这不是有效的 URL.