python - 通过遍历 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)
[[], [], [], [], []]
解决方案
重新分配要小心。虽然re.findall()
返回一个列表,并collaborators
用于列表理解,然后将其结果分配给collaborators
如果/当这些数据结构在被读取时被修改时会产生麻烦。虽然这不是主要问题。
collab
是一个空的列表列表,因为页面抓取不成功。
根本问题是DataFrame.iterrows()
. 该文档显示它返回一个索引,然后返回数据,正如 Python 所期望的那样。
因此,请检查您从中循环的返回值names.iterrows()
。
DataFrame.iterrows
返回实际上是pandas.Series
. 因此,您将需要访问first_name
和last_name
从该系列。
解包值first_name
和last_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_name
和last_name
该文档https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iterrows.html显示了 的用法iterrows()
以及它的用户可能希望考虑的内容itertuples()
。
推荐阅读
- python - 考虑对抗性输入,将积分插入 Python 的 dict() 的最坏情况时间复杂度
- javascript - 减少此代码重复性的想法?
- ios - 快速计算短时傅里叶变换
- javascript - 如何一次性打开网页表上所有基于链接的文件名并在新选项卡中打开
- javascript - 使用 Atlas Search 和 Django 构建自动完成表单元素
- javascript - 按钮上的 TamperMonkey EventListener 不起作用
- python - 在列中的最大日期结束 pandas Grouper
- javascript - React Hooks 渲染了比上一次渲染更多的钩子
- c# - 拖动物体时抖动
- python - 如何设置和保留x87浮点精度模式