【发布时间】:2019-12-21 05:23:09
【问题描述】:
我尝试从这个网站提取市盈率: https://www.ishares.com/uk/individual/en/products/251787/
我正在尝试使用我在许多网站上看到的from lxml import html 方法。
我使用tree = html.fromstring(requests.get(url))获取xpath
我使用两种不同的方法:
[1]val1 = tree.xpath(xp)
[2]val2 = tree.xpath(xp+'/text()')
这里是示例代码:
# global imports
import requests
from lxml import html
'''
function to get data given a url and xpath
'''
def aFunctionForHTML(url, xp):
#get the data
resp = requests.get(url)
if resp.status_code != 200:
# This means something went wrong.
print(resp.status_code)
return None
# generate the html tree
tree = html.fromstring(resp.content)
# get the xpath value
val1 = tree.xpath(xp)
val2 = tree.xpath(xp+'/text()')
val = (val1, val2)
return val
# the code starts here.
if __name__ == "__main__":
url = 'https://www.ishares.com/uk/individual/en/products/253741/?switchLocale=y&siteEntryPassthrough=true'
xp = '//*[@id="fundamentalsAndRisk"]/div/div[7]/span[2]'
z = aFunctionForHTML(url, xp)
print(z)
得到的值在这个<span>里面。在这种情况下 10.91。
<span class="data">
10.91
</span>
响应产生结果(使用 2 种不同的方法)。
但是返回值(作为元组)是:
([<Element span at 0x1d0dce655e8>], ['\n21.79\n'])
如何获得 10.91?
【问题讨论】:
标签: python html python-3.x web-scraping