首页 > 解决方案 > Beautiful Soup 获得 td 类的数量

问题描述

我试图从提到的网络中获取带有“名称表参与者”的 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))

标签: pythonclasshtml-tablebeautifulsoup

解决方案


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

由于提供的 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)

推荐阅读