首页 > 解决方案 > 通过遍历 pd 数据框来抓取多个网页

问题描述

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

我已经设置了空列表(“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)

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

标签: pythonpandas

解决方案


重新分配要小心。虽然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()


推荐阅读