【问题标题】:Scraping field using Beautiful soup用美汤刮地
【发布时间】:2020-04-15 22:28:47
【问题描述】:

我是网络抓取的新手。我无法从网页中获取字段(用户名)。

这是包含我感兴趣的字段的网页的 HTML。

        <div class="block-body">
          <div class="block-row block-row--separated">
          <div class="block-row block-row--separated">
            <dl class="pairs pairs--columns pairs--fixedSmall">
            <dl class="pairs pairs--columns pairs--fixedSmall">
            <dl class="pairs pairs--columns pairs--fixedSmall">
            <dl class="pairs pairs--columns pairs--fixedSmall">
            <dl class="pairs pairs--columns pairs--fixedSmall">
            <dl class="pairs pairs--columns pairs--fixedSmall">
            <dl class="pairs pairs--columns pairs--fixedSmall">
              <dt>YouTube Username</dt>
                            <dd>



                              GET_THIS_FIELD



                            </dd>
                          </dl>



            <dl class="pairs pairs--columns pairs--fixedSmall">

以下是我面临的问题:

  1. 我无法提取该字段,因为有多个对象具有相同的类,文本选项不起作用,我不知道如何找到解决方案。

  2. 由于我访问的所有页面中都没有出现 YOUTUBE USERNAME 字段,因此我需要包含一个控件。

我尝试了一切,这只是最后一次尝试。

        profile_content = profile.content 
        soup2 = BeautifulSoup(profile_content, features="lxml") 
        if soup2.find(text=re.compile('^YouTube Username$')): 
          user_channel = soup2.find("dl", {'class': 'pairs pairs--columns pairs--fixedSmall'}).find_next_siblings('dd')
        else: 
          user_channel = "none"

感谢您的帮助!

【问题讨论】:

  • edit您的问题,并将HTML部分作为代码而不是img,以便我们手动检查和验证。

标签: python web-scraping beautifulsoup


【解决方案1】:

假设 HTML 代码是正确的,我可以提供以下答案:

# data is the HTML code as string
soup = BeautifulSoup(data, 'html.parser')

the_field = soup.find('dt', string='YouTube Username').find_next('dd').text.strip()

print(the_field)

为了您自己的安全,如果找到字符串等,您可以添加测试。希望这会有所帮助。

【讨论】:

  • 非常感谢,您的评论非常有帮助,因为我意识到由于 URL 中的拼写错误,我的 HTML 没有正确加载。你让我开心!
  • 那么请帮我一个忙,给我的答案投票并将其标记为已回答。谢谢。
  • 应该有一个灰色的钩子,还有两个箭头,一个向上,一个向下。点击钩子意味着答案正确并被接受,箭头用于支持或反对答案。
猜你喜欢
  • 1970-01-01
  • 2014-05-28
  • 2020-12-18
  • 1970-01-01
  • 1970-01-01
  • 2020-02-29
  • 2021-01-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多