Python 为什么我的xpath总是得不到类似“[]”的东西?
我对爬行网页不熟悉。我的代码正在尝试获取网站的时间。我找到了位置并尝试使用xpath获取文本。但是我的代码总是返回[]。我错过什么了吗Python 为什么我的xpath总是得不到类似“[]”的东西?,python,xpath,web-crawler,Python,Xpath,Web Crawler,我对爬行网页不熟悉。我的代码正在尝试获取网站的时间。我找到了位置并尝试使用xpath获取文本。但是我的代码总是返回[]。我错过什么了吗 # -*- coding: utf-8 -*- import urllib from bs4 import BeautifulSoup from lxml import etree from lxml import html import requests headers= { 'User-Agent' : 'User-Agent:Mozilla/5.0 (W
# -*- coding: utf-8 -*-
import urllib
from bs4 import BeautifulSoup
from lxml import etree
from lxml import html
import requests
headers= { 'User-Agent' : 'User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36' }
tree = requests.get('https://www.time.gov/',headers=headers).content#.decode('utf-8')
doc_tree = etree.HTML(tree)
links = doc_tree.xpath('//div[@id="lzTextSizeCache"]/div[@class="lzswftext"]/text()')
print links
html代码的位置为:
<div class="lzswftext" style="padding: 0px; overflow: visible; width: auto; height: auto; font-weight: bold; font-style: normal; font-family: Arial, Verdana; font-size: 50px; white-space: pre; display: none;">09:37:26 a.m. </div>
您的项目是异步生成的
页面生成您要查找的项目需要一些时间。您可以在页面的源代码中看到一些指令,如setTimeOutUpdateArthImage,10000;
同样在源代码中,您可以看到您的项目不是初始页面的一部分。例如,在做卷发时
解决方案
尝试使用运行Javascript的无头浏览器,您可能还需要在代码中包含一些延迟,以便完全呈现页面。例如,或者可能您无法获得时间,因为该请求没有时间: 这是因为网页提出了另一个获取时间的请求。在这种特殊情况下,请求是,它获得以下html:
<timestamp time="1546870996756222" delay="1545324126332171"/>
要获取localzone中的时间,请读取:
这可能是一个过于复杂的解决方案,您也可以使用类似Selenium或scrapy+splash的东西,获得与您在浏览器中看到的相同的效果 你能提供相关的HTML代码片段吗?这意味着它找不到你在页面中给出的模式。期望的输出是多少?如果是在网站上显示的时间,你会知道这不是html代码中的硬编码,而是Javascript。非常详细,非常感谢
In [28]: import requests
In [29]: from datetime import datetime
In [30]: res = requests.get('https://www.time.gov/actualtime.cgi?disablecache=1546870424051&__lzbc__=wr1d55')
2019-01-07 09:34:15 [urllib3.connectionpool] DEBUG: Starting new HTTPS connection (1): www.time.gov:443
2019-01-07 09:34:16 [urllib3.connectionpool] DEBUG: https://www.time.gov:443 "GET /actualtime.cgi?disablecache=1546870424051&__lzbc__=wr1d55 HTTP/1.1" 200 None
In [31]: from bs4 import BeautifulSoup
...:
In [32]: soup = BeautifulSoup(res.text, 'html.parser')
In [34]: soup.timestamp['time']
Out[34]: '1546871656757021'
In [35]: ts = soup.timestamp['time']
In [38]: ts = int(soup.timestamp['time'])
In [39]: ts /= 1000000 # because timestamp is in microseconds
In [40]: print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))
...:
2019-01-07 14:34:16