gpt4 book ai didi

python - 使用 BeautifulSoup 解析大量 HTML 中的文本值

转载 作者:太空宇宙 更新时间:2023-11-03 14:11:13 24 4
gpt4 key购买 nike

我正在使用 Selenium 和 BeautifulSoup 手动抓取列表中的网页并保存数据。我在尝试使用 find 时遇到一些麻烦和findAll方法。

Here's the exact HTML I'm working with 。我把它发布在 Pastebin 上,因为它有很多。

如果我想提取此 HTML 中的值,例如

中的文本

<div class="item value nowrap">4 Bedrooms   3 Bathrooms</div>

或者

<td class="value" originalvalue="6229">
6,229 sq ft
</td>

我该怎么做?我尝试使用以下代码:

soup = BeautifulSoup(''.join(html))
j = soup.find('item value nowrap')[0].text
print j

我收到以下错误:

Traceback (most recent call last):
File "/Users/me/PycharmProjects/crawl/main.py", line 39, in <module>
j = soup.find('item value nowrap')[0].text
TypeError: 'NoneType' object has no attribute '__getitem__'

有人能指出我正确的方向吗?如何使用 BeautifulSoup 获取这些值?

最佳答案

这就是我要做的:

from bs4 import BeautifulSoup
html = """<html>...[paste your html here]...</html>"""
soup = BeautifulSoup(html, 'lxml')
items = soup.find_all('div', attrs={"class":'item value nowrap'})
items = [i.text for i in items]
values = soup.find_all('td', attrs={"class":"value"})
values = [i.text.strip("\n") for i in values]

find() 不会返回列表,因此您无法像尝试那样对其进行索引 (soup.find('item value nowrap')[0].text )

这就是我认为您想要找到的内容:

houses = soup.find_all('div', attrs={"class":"left factsSection basicFacts sectionSeparator"})

for house in houses:
details = house.find_all('div', attrs={"class":"item"})
print("Owner:", details[-1].find('span').text)
print("Price/sq. foot:", details[-2].find('span').text)

结果是:

Owner: Jones Patrick Clayton
Price/sq. foot: $77

关于python - 使用 BeautifulSoup 解析大量 HTML 中的文本值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48481763/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com