抓取多个网址时出现问题-NFL投注数据

时间:2019-08-29 10:49:29

标签: python pandas beautifulsoup

我有2段代码: 1st:在博彩网站上提取当前的NFL游戏 第二:提取游戏URL上的所有赌注

第一个问题是我不知道如何将它们构建为1个代码。现在,我将结果导出到Excel,并使用VBA添加URL的开头以及正确的''和逗号。我在玩地图并加入,但无法正常工作。

但是,Bigges问题是,我设置的多个URL刮擦是有问题的-因为我只从第一个刮擦中获取数据。

URL抓取:

import requests
from bs4 import BeautifulSoup
result = requests.get("https://www.betfair.com/sport/american-football")
src = result.content
soup = BeautifulSoup(src, 'lxml')

links = [a['href'] for a in soup.find_all('a',{'data-competition': "NFL Preseason Matches"},href=True)]



print(list(set(links)))
#df.to_csv('file.csv')

#str_concat = ',https://www.betfair.com'.join(list(links))

#print(list(set(links)))
#def myfunc(a, b):
#           return a + b

#x = map(myfunc, ('https://www.betfair.com','https://www.betfair.com'), (links))

多个网址抓取:

import requests
from bs4 import BeautifulSoup
import pandas as pd
urls = ['https://www.betfair.com/sport/american-football/nfl-preseason-matches/minnesota-vikings-buffalo-bills/29427759',
        'https://www.betfair.com/sport/american-football/nfl-preseason-matches/los-angeles-rams-houston-texans/29427770',
        'https://www.betfair.com/sport/american-football/nfl-preseason-matches/pittsburgh-steelers-carolina-panthers/29427758']

for url in urls:
    result2 = requests.get(url)
    src2 = result2.content
    soup = BeautifulSoup(src2, 'lxml')

data = []
for item in soup.find_all('div', {'class': 'minimarketview-content'}):
    temp_data = [ alpha for alpha in item.text.split('\n') if alpha != '' ] 
    data.append(temp_data)

df = pd.DataFrame(data)
print(df)

df.to_csv('file2.csv')

我希望所有3个URL的结果都在一个文件中,但仅显示最后一个的结果:

0,1,2,3,4,5,6,7,8
0,Pittsburgh Steelers,1.42,Carolina Panthers,2.6,,,,,
1,Pittsburgh Steelers,1.75,"-3,5",Carolina Panthers,1.95,"+3,5",,,
2,Nuværende antal points:,Over,1.8,"+33,5",Under,1.9,"+33,5",,
3,Pittsburgh Steelers,1.83,-4,Uafgjort,20.0,+4,Carolina Panthers,1.9,+4
4,Pittsburgh Steelers (-4.5) & Over (33.5) points,3.4,Pittsburgh Steelers (-4.5) og under (33.5) point,3.75,Carolina Panthers (+4.5) & Over (33.5) points,3.5,Carolina Panthers (+4.5) og under (33.5) point,3.5,

1 个答案:

答案 0 :(得分:0)

由于只覆盖soup而没有先处理并将其发送到数据,因此您只获取了最后一页。

通过处理for循环中的数据的函数,类似的方法可能会更好地工作。

仍然可以更好地编写此代码。

def process_data(soup: BeautifulSoup):
    for item in soup.find_all('div', {'class': 'minimarketview-content'}):
        temp_data = [alpha for alpha in item.text.split('\n') if alpha != '']
        data.append(temp_data)


for url in urls:
    result2 = requests.get(url)
    src2 = result2.content
    soup = BeautifulSoup(src2, 'lxml')
    process_data(soup)


df = pd.DataFrame(data)
print(df)
df.to_csv('file2.csv')

更新:

要动态获取所需链接,您必须先请求https://www.betfair.com/,然后在其中寻找

  

<div class="nav open" data-nav="All Sports" style="display: block;"/>

div包含所提供体育项目的所有类别的列表。在您要查找的列表上循环播放

  

<span>American Football</span>

然后获得下一个链接,然后重复该过程以查找您感兴趣的块,直到到达链的末尾。

要分析您感兴趣的块,请在Web浏览器中使用“检查”,右键单击您感兴趣的块,它将打开Dev Tools,您将确切地知道您要分析的块。 / p>

祝你好运

相关问题