我正在尝试通过 lxml 从网站中提取几个字符,然后是树,然后是 xpath。我试过使用谷歌浏览器来获取正确的 xpath,但它打印出空括号。
#imports
from lxml import html
import requests
#get magicseaweed Scripps report
msScrippsPage = requests.get("""http://magicseaweed.com/Scripps-Pier-
La-Jolla-Surf-Report/296/.html""")
#make tree from site
msScrippsTree = html.fromstring(msScrippsPage.content)
#get wave size
msScrippsWave = msScrippsTree.xpath("""/html/body/div[2]/div[5]/div/div[1]/div[2]/div[2]/div/div[2]/div[1]/div/div[1]/div/div/div/div/div[1]/div/div[2]/ul[1]/li[1]/text()""")
print 'ms SCripps: ', msScrippsWave
终端的输出是'msScripps: [ ]'
请您参考如下方法:
您不应该在您的网址中使用换行符。当您使用一行时,您的 xpath 工作。
msScrippsPage = requests.get("""http://magicseaweed.com/Scripps-Pier-La-Jolla-Surf-Report/296/.html""")
print msScrippsPage.content
[' 0.4-0.6', ' ']
########################################
url = """http://magicseaweed.com/Scripps-Pier-
La-Jolla-Surf-Report/296/.html"""
print url
'http://magicseaweed.com/Scripps-Pier-\n La-Jolla-Surf-Report/296/.html'
编辑:添加完整示例
from lxml import html
import requests
msScrippsPage = requests.get("""http://magicseaweed.com/Scripps-Pier-La-Jolla-Surf-Report/296/.html""")
msScrippsTree = html.fromstring(msScrippsPage.content)
msScrippsWave = msScrippsTree.xpath("""/html/body/div[2]/div[5]/div/div[1]/div[2]/div[2]/div/div[2]/div[1]/div/div[1]/div/div/div/div/div[1]/div/div[2]/ul[1]/li[1]/text()""")
print 'ms SCripps: ', msScrippsWave
