【问题标题】:How do I parse the values like this with BeutifulSoup?如何使用 BeautifulSoup 解析这样的值?
【发布时间】:2020-07-02 01:18:03
【问题描述】:

我正在尝试从网站解析一些信息,但遇到了一个小问题,我需要的信息不会打印出来,并且在我需要值时仅显示 [](例如来自提供的源代码的 3。我会需要一些帮助才能使其正常工作。希望这里有人可以帮助我并协助解决这个问题。 最好的问候。

import re
import requests
from bs4 import BeautifulSoup
url_to_parse = "https://www.webpage.com"
response = requests.get(url_to_parse)
response_text = response.text
soup = BeautifulSoup(response_text, 'lxml')
#print(soup.prettify())
ragex = re.compile('c76a6')
content_lis = soup.find_all('button', attrs={'class': ragex})
print(content_lis)

source: <button class="c76a6" type="button" data-test-name="valueButton"><span class="_5a5c0" data-test-name="value">3</span></button>

【问题讨论】:

    标签: python beautifulsoup python-requests python-re


    【解决方案1】:

    因为find_all 在数组中返回以获取项目需要对其进行索引或循环遍历匹配项,如果您知道目标是唯一的则需要时间,因此您必须使用find 获取第一个匹配项在这种情况下,您应该添加名为 text 的属性以仅获取值

    import re
    import requests
    from bs4 import BeautifulSoup
    
    url_to_parse = "https://www.webpage.com"
    response = requests.get(url_to_parse)
    response_content = response.content
    soup = BeautifulSoup(response_content, 'lxml')
    # print(soup.prettify())
    regex = re.compile('c76a6')
    content_list = soup.find('button',{'class': regex})
    print(content_list.text)
    
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-11
      • 2019-04-11
      • 2017-03-08
      • 1970-01-01
      • 2012-09-09
      • 1970-01-01
      • 2019-11-04
      相关资源
      最近更新 更多