考虑以下代码:
<div class="tag1">
<div>
<a class="tag11 tag12" href="http://www.example.com/file1" title="file1"><img class="tag2" src="http://www.example.com/img1.jpg" alt="textalt">linktext</a>
<span class="tag3">.</span>
</div>
<div>
<a class="tag11 tag12" href="http://www.example.com/file2" title="file2"><img class="tag2" src="http://www.example.com/img1.jpg" alt="textalt">linktext</a>
<span class="tag3">.</span>
</div>
这是一个较大 html 页面的部分,其中包含其他 a
带有其他标签的元素。不过,我想仅提及 a
类为 tag11 tag12
的元素并创建一个包含所有 href
的列表值(value)观。 tag11
之间有一个空格和tag12
。
使用Python 3.5,lxml
和xpath
,这是第一次尝试:
from lxml import html
import requests
page = requests.get('http://www.example.com/page.html')
tree = html.fromstring(page.content)
atest = tree.xpath('//a[contains(@class='tag11 tag12')]')
但它不起作用。使用单个顶点:
File "<stdin>", line 1
buyers = tree.xpath('//a[contains(@class='tag11 tag12')]')
^
SyntaxError: invalid syntax
使用双顶点:
tree.xpath('//a[contains(@class="tag11 tag12")]')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "src/lxml/lxml.etree.pyx", line 1587, in lxml.etree._Element.xpath (src/lxml/lxml.etree.c:61854)
File "src/lxml/xpath.pxi", line 307, in lxml.etree.XPathElementEvaluator.__call__ (src/lxml/lxml.etree.c:178516)
File "src/lxml/xpath.pxi", line 227, in lxml.etree._XPathEvaluatorBase._handle_result (src/lxml/lxml.etree.c:177421)
lxml.etree.XPathEvalError: Invalid number of arguments
另外(来自 this answer ):
atest = tree.xpath('//a[contains(@class, "tag11") and contains(@class, "tag12")]')
一个空atest
已获取列表。
如何正确处理a
元素 class
标签包含空格?
我正在使用Python 3.5,lxml
和xpath
因为我正在努力学习这些工具。因此,没有什么特别的理由不使用 BeautifulSoup,但我只是在为这些列出的工具(如果有的话)寻找特定的解决方案。
最佳答案
有什么理由不使用BeautifulSoup4吗?这是我的项目中的代码片段:
import urllib.request # You could use requests library as well
from bs4 import BeautifulSoup
url = 'http://www.example.com/page.html'
header = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
"AppleWebKit/537.36 (KHTML, like Gecko)"
"Chrome/67.0.3396.87 Safari/537.36"}
soup = BeautifulSoup(urllib.request.urlopen(
urllib.request.Request(url, headers=header)),
'lxml')
links = list()
for link in soup.find_all('a', class_='tag1 tag2'):
links.append(link.get('href'))
关于html - Python 和 xpath : identify html tags with spaced attributes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51022931/