【问题标题】:Web Scraping: How to extract href from a HTML piece?Web Scraping:如何从 HTML 片段中提取 href?
【发布时间】:2021-09-24 14:30:09
【问题描述】:

我正在尝试构建一个房地产网络抓取脚本,但我被困在如何使用来自 this 网站的 BeautifulSoup 从这段 HTML 代码中获取 href

目标元素的 HTML:

<a data-v-0354ca3a="" href="/kopa-bostad/objekt/4MDBKG9311MD8M25" class="card d-flex flex-column mb-8 v-card v-card--link v-sheet theme--light" tabindex="0" style="width: 100%;">

有什么建议吗?

谢谢!

【问题讨论】:

    标签: html web-scraping beautifulsoup


    【解决方案1】:

    BeautifulSoup 把每个 HTML 标签当作字典,你可以像这样获取&lt;a&gt; 标签的href

    from bs4 import BeautifulSoup
    
    html = '<a data-v-0354ca3a="" href="/kopa-bostad/objekt/4MDBKG9311MD8M25" class="card d-flex flex-column mb-8 v-card v-card--link v-sheet theme--light" tabindex="0" style="width: 100%;">'
    soup = BeautifulSoup(html, 'html.parser')
    for i in soup.find_all('a'):
        print(i['href'])
    

    输出:

    /kopa-bostad/objekt/4MDBKG9311MD8M25
    

    这里,for 循环中的ivariable_name_that_has_the_tag_element

    如果您只想从完整的 HTML 页面源中获取问题中提到的 HTML,请在 find_all 方法中使用 class_ 参数,或使用字典来提及 HTML 标记的类名,例如

    for i in soup.find_all('a', class_='card d-flex flex-column mb-8 v-card v-card--link v-sheet theme--light'):
        print(i['href'])
    

    或者

    for i in soup.find_all('a', {'class': 'card d-flex flex-column mb-8 v-card v-card--link v-sheet theme--light'}):
      print(i['href'])
    

    两个代码仍然输出,

    /kopa-bostad/objekt/4MDBKG9311MD8M25
    

    【讨论】:

      【解决方案2】:

      试试这个

      from bs4 import BeautifulSoup
      html = '<a data-v-0354ca3a="" href="/kopa-bostad/objekt/4MDBKG9311MD8M25" class="card d-flex flex-column mb-8 v-card v-card--link v-sheet theme--light" tabindex="0" style="width: 100%;">'
      soup = BeautifulSoup(html)
      soup.a['href']
      

      输出:

      '/kopa-bostad/objekt/4MDBKG9311MD8M25'
      

      【讨论】:

      • 谢谢!它非常适合这个,但是如何使用一些命令从完整的 html 代码中自动获取变量 html?
      • 为此,我需要查看 XPath 的 HTML 和其他内容。你能把 HTML 文件或 URL 分享给我吗?
      猜你喜欢
      • 1970-01-01
      • 2014-03-21
      • 2016-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-28
      • 2016-06-03
      相关资源
      最近更新 更多