问题描述
我到处都找了,找到的最多的就是doc.xPath(‘//Element[@class="classname"]’),但无论我怎么尝试都不管用。
我正在使用的代码
import lxml.html
def check():
data = urlopen('url').read();
return str(data);
doc = lxml.html.document_fromstring(check())
el = doc.xpath("//div[@class='test']")
print(el)
它只是打印一个空列表。
编辑: 真奇怪。我用谷歌作为测试页面,它在那里运行得很好,但它不能在我使用的页面(YouTube)上运行
这就是我正在使用的代码。
import lxml.html
from urllib.request import urlopen
import sys
def check():
data = urlopen('http://www.youtube.com/user/TopGear').read(); #TopGear as a test
return data.decode('utf-8', 'ignore');
doc = lxml.html.document_fromstring(check())
el = doc.xpath("//div[@class='channel']")
print(el)
推荐答案
您用于测试的TopGear页面没有任何<div class="channel">
元素。但这是可行的(例如):
el = doc.xpath("//div[@class='channel-title-container']")
或此:
el = doc.xpath("//div[@class='a yb xr']")
若要查找包含字符串channel
且具有class
属性的<div>
元素,您可以使用
el = doc.xpath("//div[contains(@class, 'channel')]")