【问题标题】:How to fetch/scrape all elements from a html "class" which is inside "span"?如何从“span”内的html“类”中获取/抓取所有元素?
【发布时间】:2021-03-05 17:36:23
【问题描述】:

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

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)

打印的预期结果(地点名称)

Stockholm
Malmö
Copenhagen
...
..
.

print(place_name) 得到的结果

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

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

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

【问题讨论】:

  • 请问网址是什么,您希望得到多少结果?
  • hemnet.se/salda/bostader?location_ids%5B%5D=474035 我没有预期的结果。也许以千计(猜测)
  • 我认为你的意思是“刮”。报废意味着扔掉。
  • 糟糕!我的错。那是一个拼写错误。谢谢指正!

标签: python beautifulsoup data-science


【解决方案1】:

使用循环变量而不是索引到具有相同索引 (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 标头以确保结果。另外,我注意到我必须选择一个父节点,因为使用该类 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,你需要检查每个listing有多少个子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)
    

【讨论】:

  • place_name = hit_property.find("div", {"class": "sold-property-listing__location"}).findAll("span", {"class": "item-link"} )[1] IndexError: list index out of range 如果我使用循环变量,我会遇到这个错误
  • 使用 Find,因为您现在处于单个结果级别。此外,您需要一个用户代理标头才能获得任何结果
  • 知道了。我看到这个从另一个类返回的文本而不是来自“item-link”的文本 我想从这个 Limhamns Sjöstad, 返回文本
  • 已更新。花了一段时间,因为我看到有一个列表被遗漏,并想找到一种方法来包含它。
  • 太棒了。每次都与使用正确的技术有关,这与答案无关。感谢您花时间和精力回答我的问题。干杯! :D 不要再删除你的任何答案了。它可能对其他人有用:P
猜你喜欢
  • 2020-08-02
  • 1970-01-01
  • 2021-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多