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

标签 python beautifulsoup data-science

我正在尝试从网站上抓取数据,在该网站中,我使用这段代码从“span”内的“class”下的所有元素收集数据。但我最终只获取一个元素而不是全部。

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)

打印(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 以确保结果。另外,我注意到我必须选择一个父节点,因为使用该类 item-link 至少不会捕获一个结果,例如Ö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,您需要检查每个列表有多少个子跨度标签。

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/

相关文章:

python - 在python中使用bs4从网站的不同链接获取律师详细信息

python - 如何计算指定日期内 cpf 的重复次数?

python - 在dynet中,我可以将模型保存在压缩文件中吗?

python - 如何在默认的 Sphinx 主题上使用自定义 CSS?

python - 无法从 airflow pod 中提取 xcom - Kubernetes Pod Operator

python - 将新列添加到 DataFrame 中,其值取决于索引引用

python - 如何将一组参数作为一个长变量传递给 find()/find_all()

python - SQLAlchemy ON DELETE SET NULL 同时使用辅助表

python - 如何使用 Beautiful Soup 从 HTML 文档中获取纯文本和 URL?

python - 有人在使用 pandas 加载 csv 文件时知道 "sql error"