首页 > 解决方案 > 遍历 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

任何帮助表示赞赏。

标签: pythonbeautifulsouphtml-parsing

解决方案


我的数据框列中的链接前后都有一个空格:/。就是这样。代码工作正常。只是我的疏忽。谢谢大家


推荐阅读