gpt4 book ai didi

python - Webscraping 使用 Python 返回变量值

转载 作者:行者123 更新时间:2023-12-05 06:02:42 25 4
gpt4 key购买 nike

背景

大家好...python 和网络抓取的新手。我在 Mac (Sierra) 上,在 Firefox (87.0) 中运行 Jupyter Notebook。我正在尝试从这样的网页中抓取多个值:https://www.replaypoker.com/tournaments/4337873 .我想抓取的值的一个例子是锦标赛 ID。

我尝试过的

我首先尝试使用 BeautifulSoup,但问题是此页面的许多元素并未写入 HTML。它们似乎存储在需要计算然后抓取的变量(javascript?)中,因此下面的 BeautifulSoup 代码只是将变量名称作为字符串而不是值吐出。

import bs4
import requests
from bs4 import BeautifulSoup

url = 'https://www.replaypoker.com/tournaments/4337873'
xml_soup = bs4.BeautifulSoup(response.content,'xml')
tournament_ID = html_soup.find('strong',text='Tournament ID:')
print(tournament_ID.next_sibling.strip())

当我想要 #4337873 时,它返回了 #{{id}}

在线阅读了一下,我了解到 Selenium 可以通过打开浏览器的 headless 实例来解决这个问题,所以我决定切换并使用 Selenium。问题是一旦找到正确的元素,我就不知道如何获取变量的值。

from selenium import webdriver
import time

running_tournament_url = 'https://www.replaypoker.com/tournaments/4337873'
driver = webdriver.Firefox(executable_path='/Users/maxwilliams/WebDrivers/geckodriver')
driver.get(running_tournament_url)
assert 'MTT' in driver.title

#tournament_id = driver.find_element_by_css_selector('div.col-xs-6:nth-child(1) > div:nth-child(2) > strong:nth-child(1)')
tournament_id = driver.find_element_by_xpath('/html/body/div[2]/section/div/div[1]/div[1]/div/div[1]/div[2]/strong')
print(tournament_id.text)

seats = driver.find_element_by_class_name('tournaments-seats-per-table')
print(seats.text)

time.sleep(3)
driver.quit()

此代码输出Tournament ID: 但仍然不是比赛ID 本身。我发现这特别令人困惑,因为上面的 seats 代码将打印 Seats Per Table: 9,即标签 值。

问题

  1. 我使用 Selenium 的决定是否必要且正确?还是可以通过另一个图书馆更好地实现这一目标?
  2. 如何抓取锦标赛 ID 值(以及其他类似值)?

最佳答案

该数据是从 script 标签动态提取的,这意味着您可以使用 requestsre 获取相关字符串,然后用 json。这避免了浏览器的开销。

import requests, re, json
import pandas as pd

r = requests.get('https://www.replaypoker.com/tournaments/4337873')
data = json.loads(re.search(r'RP\.data = (.*?);\n+', r.text, flags=re.S).group(1))
print(data['tournament']['id'])
df = pd.DataFrame(data['tournament']['winners'])
df.prizes = df.prizes.apply(lambda x: x[0] if x else '')
print(df)
# print(data) ## other data also present

enter image description here

关于python - Webscraping 使用 Python 返回变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66862983/

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