【问题标题】:Why does Beautifulsoup.find() not give the specific result?为什么 Beautifulsoup.find() 没有给出具体结果?
【发布时间】:2020-07-22 18:27:58
【问题描述】:

我在下面有这段代码,我试图得到 'Oswestry, England' 作为结果。

label = soup.findall('span',{'class':"ProfileHeaderCard-locationText"})
print(label)

但是,它没有给我一个价值。

HMTL 代码如下所示

<span class="ProfileHeaderCard-locationText u-dir" dir="ltr">
     <a data-place-id="5b756a1991aa8648" href="/search?q=place%3A5b756a1991aa8648">Oswestry, England</a>
     </span>

当我打印标签时,结果是我在上面发布的 HTML 代码。 ​​​ 这是我的完整代码:

import requests as req
from bs4 import BeautifulSoup

usernames = #list of username

location_list = []

for x in usernames:
    url= "https://twitter.com/" + x
    try:
        html = req.get(url)
    except Exception as e:
        print("Failed to")
        continue
    soup = BeautifulSoup(html.text,'html.parser')
    try:
        label = soup.find('span',{'class':"ProfileHeaderCard-locationText"})
        label_formatted = label.string.lstrip()
        label_formatted = label_formatted.rstrip()
        if label_formatted != "":
            location_list.append(label_formatted)
            print(x + ' : ' + label_formatted) 
        else:
            print('Not found')
    except:
        print('Not found')

【问题讨论】:

  • 您使用哪个解析器来解析 HTML 内容?
  • html.parser。尝试过 lxml 但效果不佳
  • 您是否检查过您是否使用了正确的汤方法*?
  • 使用.text打印文本
  • 该代码适用于大多数 HTML 如下所示的页面: Oswestry, England 但是,如果 HTML 代码看起来像这个 奥斯威斯特,英格兰 我再也买不到 Oswestry England。

标签: python html beautifulsoup html-parsing


【解决方案1】:

您应该调用find,而不是find_all 来获取单个元素。然后使用.text属性获取文本内容。

label = soup.find('span',{'class':"ProfileHeaderCard-locationText"})
print(label.text)

【讨论】:

  • 这也行不通。因为网站的 HTML 看起来像这样 [ 英格兰奥斯斯特里 ]
  • HTML 不在 &lt;html&gt;&lt;body&gt; 内?
【解决方案2】:

对于任何有同样问题的人,我可以通过这样做从 html 代码中获取内部数据:

label2 = soup.findAll('span',{"class":"ProfileHeaderCard-locationText"})[0].get_text()

【讨论】:

    【解决方案3】:

    您似乎正在搜索一个具有与您的查询类完全匹配的 class 属性的 span 标记。由于跨度有两个类,您的测试失败并且没有返回结果。

    使用css selectors,您可以尝试以下解决方案:

    from bs4 import BeautifulSoup as BS
    soup = BS('''<span class="ProfileHeaderCard-locationText u-dir">.....</span>''', 'html.parser')
    soup.select('span.ProfileHeaderCard-locationText')
    

    返回包含指定类的 span 标签。

    see also

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-30
      • 2015-10-07
      • 2016-03-31
      • 1970-01-01
      • 2017-07-09
      • 2018-06-04
      相关资源
      最近更新 更多