【问题标题】:How to get child value of div seperately using beautifulsoup如何使用beautifulsoup分别获取div的子值
【发布时间】:2021-09-02 07:21:41
【问题描述】:

我有一个 div 标签,其中包含三个锚标签,其中包含 url。 我可以打印这 3 个 href,但它们会合并为一个值。 有没有办法获得三个单独的值。

Div 看起来像这样:

<div class="speaker_social_wrap">
<a href="https://twitter.com/Sigve_telenor" target="_blank">
    <i aria-hidden="true" class="x-icon x-icon-twitter" data-x-icon-b=""></i>
</a>
<a href="https://no.linkedin.com/in/sigvebrekke" target="_blank">
    <i aria-hidden="true" class="x-icon x-icon-linkedin-in" data-x-icon-b=""></i>
</a>
<a href="https://www.facebook.com/sigve.telenor" target="_blank">
<i aria-hidden="true" class="x-icon x-icon-facebook-f" data-x-icon-b=""></i>
</a>

到目前为止我所尝试的:

social_media_url = soup.find_all('div', class_ = 'foo')
  for url in social_media_url:
    print(url)

预期结果:

http://twitter-url
http://linkedin-url
http://facebook-url

我的输出

<div><a twitter-url><a linkedin-url><a facebook-url></div>

【问题讨论】:

    标签: python html web-scraping beautifulsoup


    【解决方案1】:

    你可以这样做:

    from bs4 import BeautifulSoup
    import requests
    
    url = 'https://dtw.tmforum.org/speakers/sigve-brekke-2/'
    r = requests.get(url)
    soup = BeautifulSoup(r.text,'lxml')
    a = soup.find('div', class_='speaker_social_wrap').find_all('a')
    for i in a:
        print(i['href'])
    
    https://twitter.com/Sigve_telenor
    https://no.linkedin.com/in/sigvebrekke
    https://www.facebook.com/sigve.telenor
    

    【讨论】:

    • 更正了我的html..你能再检查一次吗
    • 更新了答案。请检查。
    • AttributeError: 'NoneType' 对象没有属性 'find_all' 收到此错误
    • 如果您的 HTML 代码不同,那么您显然会收到该错误。您是否复制了我的答案并运行了它?那你有没有遇到这样的错误?
    • 如果您发布您拥有的确切 HTML 代码或 URL @RaspberryLemon 会更好
    【解决方案2】:

    您的选择器为您提供 div 而不是 urls 数组。你需要更多类似的东西:

    social_media_div = soup.find_all('div', class_ = 'foo')
    social_media_anchors = social_media_div.find_all('a')
    for anchor in social_media_anchors:
      print(anchor.get('href'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-27
      • 2022-07-07
      • 1970-01-01
      • 1970-01-01
      • 2019-06-16
      • 1970-01-01
      相关资源
      最近更新 更多