我有一个简单的python脚本,例如:

#!/usr/bin/python
import requests
from lxml import html
response = requests.get('http://site.ir/')
out=response.content
tree = html.fromstring(open(out).read())
print [e.text_content() for e in tree.xpath('//div[class="group"]/div[class="groupinfo"]/a/text()')]


我使用xpath来获取标签a的值,如下图所示。

但是输出样本不是我期望的。

更新
我也有以下错误:

Traceback (most recent call last):
  File "p.py", line 7, in <module>
    tree = html.fromstring(open(out).read())
IOError: [Errno 36] File name too long: '\n<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ....

最佳答案

您需要在属性名称的开头放置@,以解决XPath中的一个属性:

//div[@class="group"]/div[@class="groupinfo"]/a/text()

关于python - 在python中通过xpath提取A标签的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26038039/

10-12 16:52
查看更多