通过遍历PD数据帧来抓取多个网页

时间:2019-03-18 20:17:14

标签: python pandas

我试图通过遍历Pandas数据框(“名称”)来抓取一组网页,该数据框包含要插入网页URL中的名字和姓氏。

我设置了空列表(“ collab”,“ freq”),以填充从每个网页提取的数据。当我仅抓取一个网页时,我的代码成功提取了数据以填充这些列表。但是,如果我遍历一个以上的网页,最终将得到空列表。

我感觉问题出在我的for循环上。谁能帮助我找出问题所在?

import pandas as pd
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
import requests
import time

first_names = pd.Series(['Ernest', 'Archie', 'Donald', 'Charles', 
'Ralph'], index = [0, 1, 2, 3, 4])
last_names = pd.Series(['Anderson', 'Higdon', 'Rock', 'Thorne', 
'Tripp'], index = [0, 1, 2, 3, 4])
names = pd.DataFrame(columns = ['first_name', 'last_name'])
names['first_name'] = first_names
names['last_name'] = last_names

collab = []
freq = []

for first_name, last_name in names.iterrows():
    url = "https://zbmath.org/authors/?q={}+{}".format(first_name, 
    last_name)
    r = requests.get(url)
    html = BeautifulSoup(r.content)
    coauthors = html.find_all('div', class_='facet1st')
    coauthors=str(coauthors)
    frequency = re.findall('Joint\sPublications">(.*?)</a>', coauthors)
    freq.append(frequency)
    collaborators = re.findall('Author\sProfile">\n(.*?)</a>', 
    coauthors)
    collaborators = [x.strip(' ') for x in collaborators]
    collab.append(collaborators)
    time.sleep(1)

print(collab)

[[],[],[],[],[]]

1 个答案:

答案 0 :(得分:0)

在重新分配时要小心。尽管re.findall()返回一个列表,并且collaborators用于列表理解,然后将其结果分配给collaborators,如果/当在读取时修改这些数据结构时,将会遇到麻烦。虽然这不是主要问题。

collab是一个空列表列表,因为页面抓取失败。

根本问题是使用DataFrame.iterrows()。该文档显示,如Python预期的那样,它先返回索引,然后返回数据。

因此,请检查您从names.iterrows()循环过来的返回值。

DataFrame.iterrows返回实际上是pandas.Series的“行”。因此,您将需要访问系列中的first_namelast_name

解压缩值first_namelast_name为:

for first_name, last_name in names.iterrows():
    print (i, type(data))

0 <class 'pandas.core.series.Series'>
1 <class 'pandas.core.series.Series'>
2 <class 'pandas.core.series.Series'>
3 <class 'pandas.core.series.Series'>
4 <class 'pandas.core.series.Series'>

last_name是一个系列,您将在其中找到first_namelast_name

此文档https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iterrows.html显示了iterrows()的用法,并且该文档的用户可能希望考虑使用itertuples()

相关问题