gpt4 book ai didi

python - 如何从 "class"内的 html "span"中获取/抓取所有元素?

转载 作者:行者123 更新时间:2023-12-04 15:03:52 24 4
gpt4 key购买 nike

我正在尝试从一个网站抓取数据,我正在使用这段代码从“类”下的所有元素收集数据,这些元素位于“跨度”内。但我最终只获取了一个元素而不是所有元素。

expand_hits = soup.findAll("a", {"class": "sold-property-listing"})
apartments = []
for hit_property in expand_hits:
#element = soup.findAll("div", {"class": "sold-property-listing__location"})
place_name = expand_hits[1].find("div", {"class": "sold-property-listing__location"}).findAll("span", {"class": "item-link"})[1].getText()
print(place_name)
apartments.append(final_str)

print(place_name) 的预期结果

Stockholm
Malmö
Copenhagen
...
..
.

打印(place_name) 的结果

Malmö
Malmö
Malmö
...
..
.

当我尝试从 expand_hits[1] 获取内容时,我只得到一个元素。如果我不指定索引抓取器会抛出有关使用 find()、find_all() 和 findAll() 的错误。据我所知,我认为我必须迭代地调用元素的内容。

非常感谢任何帮助。提前致谢!

最佳答案

使用循环变量而不是索引到具有相同索引的相同集合(expand_hits[1])并附加 place_name 而不是 final_str

expand_hits = soup.findAll("a", {"class": "sold-property-listing"})
apartments = []
for hit_property in expand_hits:
place_name = hit_property.find("div", {"class": "sold-property-listing__location"}).find("span", {"class": "item-link"}).getText()
print(place_name)
apartments.append(place_name)

你只需要查找而不需要索引


添加 User-Agent header 以确保结果。另外,我注意到我必须选择一个父节点,因为使用该类项目链接至少不会捕获一个结果,例如Övägen 6C。我使用替换来消除由于现在选择父节点而出现的隐藏文本。

from bs4 import BeautifulSoup 
import requests
import re

url = "https://www.hemnet.se/salda/bostader?location_ids%5B%5D=474035"
page = requests.get(url, headers = {'User-Agent':'Mozilla/5.0'})
soup = BeautifulSoup(page.content,'html.parser')

for result in soup.select('.sold-results__normal-hit'):
print(re.sub(r'\s{2,}',' ', result.select_one('.sold-property-listing__location h2 + div').text).replace(result.select_one('.hide-element').text.strip(), ''))

如果您只想要马尔默的某个地方,例如 Limhamns Sjöstad,您需要检查每个列表有多少个子 span 标签。

for result in soup.select('.sold-results__normal-hit'):
nodes = result.select('.sold-property-listing__location h2 + div span')
if len(nodes)==2:
place = nodes[1].text.strip()
else:
place = 'not specified'
print(place)

关于python - 如何从 "class"内的 html "span"中获取/抓取所有元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66497106/

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