gpt4 book ai didi

python - 如何从比分直播中抓取足球成绩?

转载 作者:太空宇宙 更新时间:2023-11-03 15:52:05 32 4
gpt4 key购买 nike

我有这个项目正在使用 python 3.4。我想在 livescore.com 上抓取足球比分(结果),例如获取当天的所有比分(英格兰 2-2 挪威,法国 2-1 意大利等)。我正在使用 python 3.4、windows 10 64 位操作系统构建它。

我试过两种方法,这是代码:

import bs4 as bs
import urllib.request

sauce = urllib.request.urlopen('http://www.livescore.com/').read()
soup = bs.BeautifulSoup(sauce,'lxml')

for div in soup.find_all('div', class_='container'):
print(div.text)

当我运行这段代码时,一只盒子里的小狗说:

IDLE's subprocess didn't make connection. Either IDLE can't start a subprocess or firewall software is blocking the connection.

我决定再写一个这是代码:

# Import Modules
import urllib.request
import re

# Downloading Live Score XML Code From Website and reading also
xml_data = urllib.request.urlopen('http://static.cricinfo.com/rss/livescores.xml').read()

# Pattern For Searching Score and link
pattern = "<item>(.*?)</item>"

# Finding Matches
for i in re.findall(pattern, xml_data, re.DOTALL):
result = re.split('<.+?>',i)
print (result[1], result[3]) # Print Score

我得到了这个错误:

Traceback (most recent call last):
File "C:\Users\Bright\Desktop\live_score.py", line 12, in <module>
for i in re.findall(pattern, xml_data, re.DOTALL):
File "C:\Python34\lib\re.py", line 206, in findall
return _compile(pattern, flags).findall(string)
TypeError: can't use a string pattern on a bytes-like object

最佳答案

在您的第一个示例中 - 该网站正在通过大量 javascript 加载其内容,因此我建议使用 selenium 来获取源代码。

您的代码应如下所示:

import bs4 as bs
from selenium import webdriver

url = 'http://www.livescore.com/'
browser = webdriver.Chrome()
browser.get(url)
sauce = browser.page_source
browser.quit()
soup = bs.BeautifulSoup(sauce,'lxml')

for div in soup.find('div', attrs={'data-type': 'container'}).find_all('div'):
print(div.text)

对于第二个例子,正则表达式引擎返回一个错误,因为你的请求中的 read() 函数给出了字节数据类型,“re”只接受字符串或 unicode。因此,您只需将 xml_data 强制转换为 str。

这是修改后的代码:

for i in re.findall(pattern, str(xml_data), re.DOTALL):
result = re.split('<.+?>',i)
print (result[1], result[3]) # Print Score

关于python - 如何从比分直播中抓取足球成绩?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46045170/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com