【问题标题】:Loop through a python dataframe with 10 urls and extract contents from them (BeautifulSoup)循环遍历具有 10 个 url 的 python 数据框并从中提取内容 (BeautifulSoup)
【发布时间】:2017-02-15 13:13:57
【问题描述】:

我有一个名为“df”的 csv,有 1 列。我有一个标题和 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')))

【问题讨论】:

    标签: python beautifulsoup urllib2


    【解决方案1】:

    固定答案

    我没有意识到你在使用pandas,所以我说的不是很有帮助。

    您希望使用pandas 执行此操作的方式是遍历行并从中提取信息。以下应该可以工作而不必摆脱标题:

    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 文件的标头似乎没有被单独处理,因此在第一次迭代中通过 df_link,link[0] 是 "Col",这不是一个有效的 URL。

    【讨论】:

    • 那么我应该删除标题吗?或者我应该使用链接[1]。我会同时尝试并更新。
    • 我做了一个关于你做错了什么的假设......我已经更新了我的答案!
    • 谢谢你..我一定会在我尝试后回复你:)
    • 工作 :) 谢谢。我终于切换到相同的请求包!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-13
    • 1970-01-01
    • 2018-03-16
    • 2018-08-27
    • 2020-02-14
    • 2019-04-24
    相关资源
    最近更新 更多