python - 使用美汤进行网页抓取(体育数据)
问题描述
当我尝试加载此代码时,出现两个错误。1:第一个是我无法正确抓取name_text的数据。
2:我收到 team = name_text.div.text 的缩进错误。我知道这可能很容易解决,但我尝试了不同的缩进,但似乎没有任何效果。
在网站上,我想抓取球队名称和赔率。
<div class="size14_f7opyze Endeavour_fhudrb0 medium_f1wf24vo participantText_fivg86r" data-automation-id="participant-one">Orlando Magic</div>
<div class="priceText_f71sibe"><span class="size14_f7opyze medium_f1wf24vo priceTextSize_frw9zm9" data-automation-id="price-text">5.85</span></div>
上面的html是从网站上复制的。
from bs4 import BeautifulSoup
from urllib.request import urlopen as uReq
my_url = 'https://www.sportsbet.com.au/betting/basketball-us'
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()
soup = BeautifulSoup(page_html, "html.parser")
price_text = soup.findAll("div",{"class":"priceText_f71sibe"})
name_text = soup.findAll("div",{"class":"size14_f7opyze Endeavour_fhudrb0 medium_f1wf24vo participantText_fivg86r"})
filename = "odds.csv"
f = open(filename,"w")
headers = "Team, odds_team\n"
print(name_text)
f.write(headers)
for price_text in price_texts:
team = name_text.div.text
odds = price_text.span.text
print(odds)
print(team + odds)
f.write(team + "," + odds + "\n")
f.close()
任何帮助都会很棒。干杯。
解决方案
您的for loop
缩进不正确。正确的缩进是:
for price_text in price_texts:
team = name_text.div.text
odds = price_text.span.text
team = name_text.div.text
odds = price_text.span.text
print(odds)
print(team + odds)
f.write(team + "," + odds + "\n")
f.close()
队前有 4 个空格和赔率。请阅读Python ForLoop 文档。
此外,没有price_texts
变量。当你做findAll时你需要分配它,你忘记了一个'S':
price_texts = soup.findAll("div",{"class":"priceText_f71sibe"})
最后一件事,考虑使用with
而不是open()
和.close()
写入您的文件。
推荐阅读
- azure - 用于管理数百万订阅者(即客户)的 Webhook 架构
- c# - C# FileVersionInfo.GetVersionInfo (FilePath) 行为异常
- swift - 为什么 Swift 编译器不能推断类型?
- android - Google Play 管理中心:如何将 Android 应用从 Alpha 升级到 Beta
- routing - IE11 的 Angular6 路由问题
- javascript - 承诺事件全球?
- python - 如何测量两个非线性时间序列数据集之间的相关性
- r - 使用 `withCallingHandlers` 并行出错
- windows - 如何在powershell命令中设置变量
- ruby-on-rails - 无法连接到 Ubuntu 16.04.5 LTS 上的 Rails 服务器