【发布时间】:2020-10-03 15:41:48
【问题描述】:
这应该不会太难,虽然我想不通,但我敢打赌我犯了一个愚蠢的错误。
这是适用于单个链接并返回 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
感谢任何帮助。
【问题讨论】:
-
您确定发送给 BS 的链接有效吗?试试
for link in df['links']: print(link),看看这些是不是你需要的链接。 -
@JackFleeting 是的,好主意,但它正在从数据框中打印出链接,并且这些链接是有效的。你可以在 jupyter 中点击它们,它们就可以工作了。
-
在这种情况下,这可能意味着(至少)其中一个 url 的汤没有
'h4:contains("Home value")。如果从 df 中删除该 url,则循环应该可以工作(直到它运行到没有该标记的下一个 url)。 -
从您的错误看来,结果 = test_soup.select_one('h4:contains("Home value")') 正在返回 None 类型。所以首先检查结果是否存在,如果存在则进行下一个操作
results = test_soup.select_one('h4:contains("Home value")') if results: p_tag = results.find_next('p') if p_tag: value=get_text(strip=True)然后将值添加到数据框列
标签: python beautifulsoup html-parsing