【问题标题】:Beautiful Soup Obtain number of td classBeautiful Soup 获得 td 类的数量
【发布时间】:2019-05-14 23:55:36
【问题描述】:

我正在尝试从上述网络获取具有“名称表参与者”的 td 类的数量,但没有成功,因为我得到了 0。 有什么帮助吗?

谢谢


from requests import get
url = 'https://www.oddsportal.com/soccer/spain/laliga/'
response = get(url)

from bs4 import BeautifulSoup
html_soup = BeautifulSoup(response.text, 'html.parser')
type(html_soup)

movie_containers = html_soup.find_all('td', class_ = 'name table-participant')
print(type(movie_containers))
print(len(movie_containers))

【问题讨论】:

    标签: python class html-table beautifulsoup


    【解决方案1】:

    实际上,您的代码没有问题,但您没有检查 GET 请求中的状态代码。发生的事情是服务器正在回复一个不错的404,并且一个页面不包含您要查找的内容。原因?我不知道。

    由于提供的 URL 确实在浏览器中工作,我只需将 User-Agent 标头添加到调用中,您的代码就开始工作了。要添加 User-Agent,您可以执行以下操作:

    from requests import get
    from bs4 import BeautifulSoup
    
    headers = {'User-Agent': 'Mozilla/5.0'}
    url = 'https://www.oddsportal.com/soccer/spain/laliga/'
    response = get(url, headers=headers)
    
    if response.status_code == 200:
        html_soup = BeautifulSoup(response.text, 'html.parser')
        movie_containers = html_soup.find_all('td', class_ = 'name table-participant')
        print(type(movie_containers))
        print(len(movie_containers))
    else:
        print("Server returned status code %s" % response.status_code)
    

    【讨论】:

    • 非常感谢!我没有收到任何错误。您如何看到 404 错误?
    • @Lander 在完成response = get(url) 之后,我检查了response.status_code,发现它是404 而不是200
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    • 2018-03-31
    • 2018-02-02
    相关资源
    最近更新 更多