gpt4 book ai didi

python - 保存麻烦的网页并导入回Python

转载 作者:行者123 更新时间:2023-12-01 08:40:09 25 4
gpt4 key购买 nike

我正在尝试从各个页面中提取一些信息,但有点困难。这显示了我的挑战:

import requests
from lxml import html
url = "https://www.soccer24.com/match/C4RB2hO0/#match-summary"
response = requests.get(url)
print(response.content)

如果将输出复制到记事本中,则在输出中的任何位置都找不到值“9.20”(网页右下角的 A 队赔率)。但是,如果您打开网页,执行另存为,然后将其导入回 Python,如下所示,您可以找到并提取 9.20 值:

with open(r'HUL 1-7 TOT _ Hull - Tottenham _ Match Summary.html', "r") as f:
    page = f.read()
tree = html.fromstring(page)

output = tree.xpath('//*[@id="default-odds"]/tbody/tr/td[2]/span/span[2]/span/text()')  #the xpath for the TeamA odds or the 9.20 value
output # ['9.20']

不知道为什么这个解决方法有效,但这超出了我的范围。所以我想做的是将网页保存到本地驱动器并用 Python 打开它,如上所述,然后从那里继续。但是如何在 Python 中复制另存为呢?这不起作用:

import urllib.request
response = urllib.request.urlopen(url)
webContent = response.read().decode('utf-8')
f = open('HUL 1-7 TOT _ Hull - Tottenham _ Match Summary.html', 'w')
f.write(webContent)
f.flush()
f.close()

它给了我一个网页,但它只是原始页面的一小部分......?

最佳答案

正如@Pedro Lobito所说。页面内容由javascript生成。因此,您需要一个可以运行 JavaScript 的模块。我会选择 requests_htmlselenium

Requests_html

from requests_html import HTMLSession

url = "https://www.soccer24.com/match/C4RB2hO0/#match-summary"

session = HTMLSession()
response = session.get(url)
response.html.render()
result = response.html.xpath('//*[@id="default-odds"]/tbody/tr/td[2]/span/span[2]/span/text()')
print(result)
#['9.20']

Selenium

from selenium import webdriver
from lxml import html

url = "https://www.soccer24.com/match/C4RB2hO0/#match-summary"
dr = webdriver.Chrome()

try:
dr.get(url)
tree = html.fromstring(dr.page_source)
''' use it when browser closes before loading succeeds
# https://selenium-python.readthedocs.io/waits.html
WebDriverWait(dr, 10).until(
EC.presence_of_element_located((By.ID, "myDynamicElement"))
)
'''
output = tree.xpath('//*[@id="default-odds"]/tbody/tr/td[2]/span/span[2]/span/text()') #the xpath for the TeamA odds or the 9.20 value
print(output)

except Exception as e:
raise e

finally:
dr.close()
#['9.20']

关于python - 保存麻烦的网页并导入回Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53544345/

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