【问题标题】:Can't figure how to web-scraping using beautifulsoup不知道如何使用 beautifulsoup 进行网页抓取
【发布时间】:2018-06-20 14:27:00
【问题描述】:

我正在尝试从某个网页上抓取以下信息。这是完整的代码:

<tr class="owner">
   <td id="P184" class="ownerP" colspan="4">
      <ul>
         <li><span class="detailType">name:</span><span class="detail">merry/span></li>
         <li><a title="sendmessage" class="sendMessageLink" onclick="return openSendMessage('/sendMessage.php',20205" href="" tabindex="0"><span></span>sendmessage</a>&nbsp;<span class="remark_soft">(by pm system)</span></li>
         <li><span class="detailType">phone 1</span><a class="detail" href="tel:0387362531">0387362531</a></li>
         <li><span class="detailType"></span></li>
      </ul>
   </td>
</tr>

我只想获取此信息(电话号码):

<a class="detail" href="tel:0387362531">0387362531</a>

这是我的代码,但它不起作用:

 for details in soup.find_all(attrs= {"class": "detail"}):
    re_res = re.search(r"tel:\('.*?',(\d+)\)", details['href'])
    print(re_res)

【问题讨论】:

    标签: python regex beautifulsoup


    【解决方案1】:

    你已经很接近了,给你:

    import re
    from bs4 import BeautifulSoup
    
    html_doc = """
    <tr class="owner"><td id="P184" class="ownerP" colspan="4"><ul>
                <li><span class="detailType">name:</span><span class="detail">merry/span></li>
                <li><a title="sendmessage" class="sendMessageLink" onclick="return openSendMessage('/sendMessage.php',20205" href="" tabindex="0"><span></span>sendmessage</a>&nbsp;<span class="remark_soft">(by pm system)</span></li><li><span class="detailType">phone 1</span><a class="detail" href="tel:0387362531">0387362531</a></li><li><span class="detailType"></span></li>
    </ul></td></tr>
    """
    
    soup = BeautifulSoup(html_doc, 'html.parser')
    
    for details in soup.find_all(attrs= {"class": "detail"}):
        if "href" in details.attrs and re.search("^tel:", details.attrs["href"]):
            print(details.text)
    

    输出:

    0387362531
    

    我只是在查看您创建的详细信息列表,如果我找到一个有 href 并且 hreftel: 开头的列表,则打印出该值。

    【讨论】:

      【解决方案2】:

      您应该将soup.find_all(attrs= {"class": "detail"}) 替换为soup.find_all('a', attrs= {"class": "detail"})[0],以避免span 也出现在details 中。

      此外,您的正则表达式不起作用,这个应该可以工作tel:(\d+)。但是,与其使用正则表达式,为什么不通过执行 details.text 来获取 a 标记文本?

      【讨论】:

        【解决方案3】:

        您必须将元素类型 a 添加到 find_all 并且您的正则表达式 tel:\('.*?',(\d+)\) 尝试匹配不在 href 中的左括号和右括号 \(\)

        您可以将您的正则表达式更新为 tel:(\d+) 以匹配 tel: 后跟捕获组(组 1)中的一个或多个数字,您可以使用 re_res.group(1) 检索这些数字

        例如:

        for details in soup.find_all('a', attrs= {"class": "detail"}):
            re_res = re.search(r"tel:(\d+)", details['href'])
            print(re_res.group(1))  # 0387362531
        

        【讨论】:

          【解决方案4】:

          您可以在不使用正则表达式的情况下获得相同的结果。在这种情况下,请尝试以下方法:

          from bs4 import BeautifulSoup
          
          html_doc = """
          <tr class="owner"><td id="P184" class="ownerP" colspan="4"><ul>
                      <li><span class="detailType">name:</span><span class="detail">merry/span></li>
                      <li><a title="sendmessage" class="sendMessageLink" onclick="return openSendMessage('/sendMessage.php',20205" href="" tabindex="0"><span></span>sendmessage</a>&nbsp;<span class="remark_soft">(by pm system)</span></li><li><span class="detailType">phone 1</span><a class="detail" href="tel:0387362531">0387362531</a></li><li><span class="detailType"></span></li>
          </ul></td></tr>
          """
          

          使用.select()

          soup = BeautifulSoup(html_doc, 'html.parser')
          for telephone in soup.select("a[href^='tel:']"):
              if "detail" in telephone['class']:
                  print(telephone.text)
          

          或者.find_all():

          soup = BeautifulSoup(html_doc, 'html.parser')
          for telephone in soup.find_all("a",class_="detail"):
              if telephone['href'].startswith('tel:'):
                  print(telephone.text)
          

          它们都产生相同的输出:

          0387362531
          

          【讨论】:

            猜你喜欢
            • 2018-08-02
            • 1970-01-01
            • 2020-10-04
            • 2021-01-31
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-08-01
            相关资源
            最近更新 更多