python - 遍历 URL 的 Dataframe 列并解析出 html 标签
问题描述
这不应该太难,虽然我想不通,但我打赌我犯了一个愚蠢的错误。
这是适用于单个链接并返回 zestimate 的代码(req_headers 变量可防止引发验证码):
req_headers = {
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'en-US,en;q=0.8',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'
}
link = 'https://www.zillow.com/homedetails/1404-Clearwing-Cir-Georgetown-TX-78626/121721750_zpid/'
test_soup = BeautifulSoup(requests.get(link, headers=req_headers).content, 'html.parser')
results = test_soup.select_one('h4:contains("Home value")').find_next('p').get_text(strip=True)
print(results)
这是我试图开始工作并返回每个链接的 zestimate 并添加到新的数据框列的代码,但我得到AttributeError: 'NoneType' object has no attribute 'find_next'
了(另外,假设我有一个不同 zillow 房屋链接的数据框列):
req_headers = {
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'en-US,en;q=0.8',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'
}
for link in df['links']:
test_soup = BeautifulSoup(requests.get(link, headers=req_headers).content, 'html.parser')
results = test_soup.select_one('h4:contains("Home value")').find_next('p').get_text(strip=True)
df['zestimate'] = results
任何帮助表示赞赏。
解决方案
我的数据框列中的链接前后都有一个空格:/。就是这样。代码工作正常。只是我的疏忽。谢谢大家
推荐阅读
- django - Django allauth Social application accessing extra data
- python - 在比较不同长度的 2 个数据帧中的值后添加列
- laravel - Laravel Api Documentation Genarator
- java - how to skip a character when read strings from a file in Java
- java - 类转换异常:不能转换为类
- android - Android使用ChildEventListener从firebase获取新消息
- javascript - How to send array of file objects through ajax with form serialize()?
- c++ - 如何在 C 或 C++ 中实现 tss2 API 以在代码中使用功能
- node.js - Swagger UI 在 NodeJS 中无法正确呈现
- javascript - 为什么不迭代?