使用Python和beautifulsoup进行Web抓取:beautifulsoup函数保存了什么?

2024-06-15 00:20:54 发布

您现在位置:Python中文网/ 问答频道 /正文

这个问题紧随其后。我想使用Python从一个博彩网站上抓取数据。我第一次尝试遵循这个tutorial,但问题是tipico网站无法从瑞士获得。因此,我选择了另一个博彩网站:Winamax。在本教程中,首先检查网页tipico,以便找到投注率在html文件中的位置。在tipico网页中,它们存储在“c_but_base c_but”类的按钮中。通过编写以下行,可以使用Beauty soup模块保存和打印费率:

from bs4 import BeautifulSoup
import urllib.request
import re

url = "https://www.tipico.de/de/live-wetten/"

try:
 page = urllib.request.urlopen(url)
except:
 print(“An error occured.”)

soup = BeautifulSoup(page, ‘html.parser’)

regex = re.compile(‘c_but_base c_but’)
content_lis = soup.find_all(‘button’, attrs={‘class’: regex})
print(content_lis)

因此,我尝试对网页Winamax进行同样的操作。我检查了该网页,发现投注率存储在“ui touchlink needsclick price Oddle price”类的按钮中。请参见下面的代码:

from bs4 import BeautifulSoup
import urllib.request
import re

url = "https://www.winamax.fr/paris-sportifs/sports/1/7/4"

try:
    page = urllib.request.urlopen(url)
except Exception as e:
    print(f"An error occurred: {e}")

soup = BeautifulSoup(page, 'html.parser')

regex = re.compile('ui-touchlink-needsclick price odd-price')
content_lis = soup.find_all('button', attrs={'class': regex})
print(content_lis)

问题是它什么也不打印:Python找不到此类的元素(对吗?)。因此,我尝试打印soup对象,以查看BeautifulSoup函数到底在做什么。我添加了这一行

print(soup)

在打印时(因为太长,我没有显示“汤”的打印),我注意到这与我右键单击Winamax网页“检查”时显示的文本不同。那么BeautifulSoup函数到底在做什么?我如何使用BeautifulSoup存储Winamax网站的投注率

编辑:我从来没有用html编写过代码,而且我是Python的初学者,所以有些术语可能是错误的,这就是为什么有些部分用斜体


Tags: importreurl网页网站requesthtmlpage
1条回答
网友
1楼 · 发布于 2024-06-15 00:20:54

这是因为该网站正在使用JavaScript来显示这些详细信息,而BeautifulSoup本身并不与JS进行交互

首先试着找出你想要刮取的元素是否存在于页面源代码中,如果是这样,你可以刮取,几乎所有的东西!在您的情况下,按钮/span标记不在页面源中(表示隐藏或通过脚本提取)

页面源中没有<button>标记: enter image description here

因此,我建议使用硒作为解决方案,并尝试了网站的基本刮擦

以下是我使用的代码:

from selenium import webdriver

option = webdriver.ChromeOptions()
option.add_argument(' headless')
option.binary_location = r'Your chrome.exe file path'

browser = webdriver.Chrome(executable_path=r'Your chromedriver.exe file path', options=option)

browser.get(r"https://www.winamax.fr/paris-sportifs/sports/1/7/4")

span_tags = browser.find_elements_by_tag_name('span')
for span_tag in span_tags:
    print(span_tag.text)

browser.quit()

这是输出:

enter image description here

此输出中存在一些垃圾数据,但这是为了让您了解您需要什么和不需要什么

相关问题 更多 >