【问题标题】:Beautiful soup find href not working美丽的汤发现href不起作用
【发布时间】:2018-07-17 18:17:01
【问题描述】:

我是 Python 编码的新手,但到目前为止,我使用 bs4 编写了一些简单的爬虫。我在某个特定项目上遇到了问题:

page = requests.get("http://www.radarindustrial.com.br/empresa/19640/")
soup = BeautifulSoup(page.content, 'html.parser')

web = soup.find_all(href = True, id = "contatos")

它返回 [ ]。当我只尝试

web = soup.find_all(id = "contatos")

它返回(正确)我需要的 div,它包含一个 href(我插入点只是为了显示我需要的代码部分,即那个 URL)

<.a href="/Redirect.aspx?cid=19640&url=<a%20href=" http: rel="nofollow" target="_blank">http://www.ashtarbrindes.com.br" target="]

我尝试过“web.a”、find(“a”, id="contatos") 和其他方法,但它返回一个空列表或“none”。

我在搞砸什么?

【问题讨论】:

  • 那么,您需要在div 中获取a 标签,其中id 等于contatos?试试web = soup.find("div", {"id": "contatos"}).select_one("a")
  • 嘿,谢谢,这行得通,现在我只需要获取标签内的 url :)

标签: regex python-3.x beautifulsoup


【解决方案1】:

你可以使用

>>> web = soup.find("div", {"id": "contatos"}).select_one('a["href"]')['href']
>>> web
'/Redirect.aspx?cid=19640&url=http://www.ashtarbrindes.com.br'

使用.find("div", {"id": "contatos"}),您将提取id 等于contatosdiv,然后.select_one('a["href"]') 将在div 中找到包含href['href'] 的第一个a 标记将访问href 属性值。

【讨论】:

    【解决方案2】:

    如果我们对 css 没问题,那么:

    soup.select_one('div#contatos a[href]')['href']
    

    【讨论】:

      猜你喜欢
      • 2018-05-08
      • 2016-12-18
      • 2023-03-27
      • 1970-01-01
      • 2011-11-15
      • 2018-07-31
      • 2020-06-24
      • 1970-01-01
      • 2021-09-23
      相关资源
      最近更新 更多