【问题标题】:How to extract only a specific kind of link from a webpage with beautifulsoup4如何使用beautifulsoup4从网页中仅提取特定类型的链接
【发布时间】:2020-03-22 19:26:55
【问题描述】:

我正在尝试在充满链接的页面上提取特定链接。我需要的链接中包含“公寓”一词。

但无论我尝试什么,我提取的数据远远多于我需要的链接。

<a href="https://www.website.com/en/ad/apartment/abcd123" title target="IWEB_MAIN">

如果有人能帮助我解决这个问题,将不胜感激! 此外,如果您有一个很好的消息来源可以更好地告知我这一点,我们将不胜感激!

【问题讨论】:

  • 先提取所有的锚标签,然后用你想要的关键字过滤。

标签: python web-scraping beautifulsoup screen-scraping


【解决方案1】:

你可以使用正则表达式re。

import re
soup=BeautifulSoup(Pagesource,'html.parser')
alltags=soup.find_all("a",attrs={"href" : re.compile("apartment")})
for item in alltags:
    print(item['href']) #grab href value

或者你可以使用css选择器

soup=BeautifulSoup(Pagesource,'html.parser')
alltags=soup.select("a[href*='apartment']")
for item in alltags:
    print(item['href'])

详情请看官方文档Beautifulsoup

已编辑

你需要先考虑父div,然后找到锚标签。

import requests
from bs4 import BeautifulSoup
res=requests.get("https://www.immoweb.be/en/search/apartment/for-sale/leuven/3000")
soup = BeautifulSoup(res.text, 'html.parser')
for item in soup.select("div[data-type='resultgallery-resultitem'] >a[href*='apartment']"):
       print(item['href'])

【讨论】:

  • 我整天都在他们的官方文件上经历了很多事情,但我对这件事太陌生了,无法做到这一点,因为我仍然无法做到。我会试试你的方法,看看是否有效!谢谢你:)
  • @MoofinTheExplorer:让我知道进展如何。
  • 我已经尝试了这两种方法,但它只是返回我'进程以退出代码 0 完成'。我整天都在尝试使用scrapy来完成工作,但也没有成功……也许是网站的html太分层了,这让它变得超级困难?
  • @MoofinTheExplorer : 可以分享一下网址吗?
  • immoweb.be/en/search/apartment/for-sale/leuven/3000 我越来越接近了,我终于找到了如何提取一些关键字,这对我来说是朝着正确方向迈出的一大步,很快我将解决链接问题我的新知识,看看我是否能做到这一点。
猜你喜欢
  • 2018-08-14
  • 1970-01-01
  • 1970-01-01
  • 2021-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-18
相关资源
最近更新 更多