【问题标题】:Issues with selecting #text inside an html, div enclosed in double quotes using xpath/lxml in python在 python 中使用 xpath/lxml 在 html 中选择 #text 时出现问题,div 用双引号括起来
【发布时间】:2021-02-04 10:18:46
【问题描述】:

我正在尝试使用 python 提取以下Yahoo Finance page 上的基金摘要文本:

到目前为止,XPath 使用带有text() 方法的XPath 运行良好。但是它似乎无法选择这个特定的文本,总是输出一个空数组[]

我尝试了以下 xpath:

  • tree.xpath("//*[@id='Col2-4-QuoteModule-Proxy']/div/div/div/text())
  • tree.xpath('//*[@data-yaft-module="tdv2-applet-fundSummary"]/div/div/text()')

#text 是否有一些需要以不同方式定位的内容?我在那里使用的第一个 XPath 是直接从检查元素复制的。所以我不确定如何选择它。

【问题讨论】:

  • 如果禁用 Javascript,页面是否包含/显示浏览器中的数据?如今,网页中的许多内容都是使用 Javascript 动态加载的,因此像 lxml 这样的解析器在不运行 Javascript 的情况下加载静态 HTML 文档将不会有任何由 Javascript 加载的数据。
  • 是的,当我禁用 JS 时它仍然显示。
  • 你能不能更具体一点,你是想在主页还是在市场内找到这个值?大多数情况下,您需要的所有信息都在 json 或脚本中发送,请尝试在 HTML 或 json 响应中搜索您要查找的值并从那里提取它们
  • 对站点的普通请求的响应包含一个带有变量“App.main”的脚本,其中包含一个 JSON,其中包含摘要中列出的所有信息。如果您希望提取实时数据,更好的解决方案是从 wss://streamer.finance.yahoo.com/ 捕获 websocket 响应

标签: python html xpath lxml screen-scraping


【解决方案1】:

你可以试试这样的

import json
import requests
from bs4 import BeautifulSoup

# get the page
r = requests.get('https://ca.finance.yahoo.com/quote/VUN.TO?p=VUN.TO')
soup = BeautifulSoup(r.text, 'lxml')

# find the script we want
js_delimiter = 'App.main = '
for s in soup.find_all('script'):
    if js_delimiter in s.text:
        myS = s.text
# load it as a json
js_variable = json.loads(myS.split(js_delimiter)[-1].split(';\n')[0])

# now js_variable contains all the content of the page
print(js_variable['context']['dispatcher']['stores']['StreamDataStore']['quoteData']['VUN.TO']['regularMarketPreviousClose']['fmt'])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 2012-07-29
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多