【问题标题】:Save troublesome webpage and import back into Python保存麻烦的网页并重新导入 Python
【发布时间】:2019-05-01 19:56:07
【问题描述】:

我正在尝试从各种页面中提取一些信息并且有点挣扎。这显示了我的挑战:

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()

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

【问题讨论】:

  • 可能是javascript生成的。

标签: python html python-requests lxml save-as


【解决方案1】:

正如@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']

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']

【讨论】:

  • 感谢!我需要在 Google Colab 中使用它,但遇到错误(浏览器意外关闭),但我会为此打开另一个问题。
猜你喜欢
  • 1970-01-01
  • 2017-04-10
  • 2014-06-28
  • 2011-01-18
  • 2012-08-23
  • 2015-02-18
  • 1970-01-01
  • 1970-01-01
  • 2018-10-29
相关资源
最近更新 更多