python - 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))
解决方案
实际上,您的代码没有问题,但您没有检查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)
推荐阅读
- intellij-idea - Jupyter Notebook setup in IntelliJ IDEA
- php - WooCommerce editable custom checkout field and displayed in formatted address
- r - Fill in missing values (nacof/nocb) in character column by group
- typescript - how to change the particular marker color in angular maps
- java - Spring Boot Rest + ClearDB mySQL "exceeded 'max_user_connections'" error
- amazon-web-services - pm2: command not found after npm -g
- r - 如何消除 for 循环中的最大值以满足特定条件?
- python - 合并几个字典,在不同的值上创建数组
- android - 我们可以显示从 Play 商店开发者帐户弹出的应用程序“维护/服务已禁用”吗?
- serialization - 如何在 Lua 中序列化元表?