用lxm解析HTML数据

2024-09-27 02:20:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个编程初学者,我的一个朋友告诉我使用beauthoulsoup而不是htmlparser。遇到一些问题后,我得到了一个建议,用lxml代替BeaytifulSoup,因为它比BeaytifulSoup好10倍。在

我希望有人能给我一个提示,如何擦掉我要找的文本。在

我想要的是找到一个包含以下行和数据的表:

<tr>
    <td><a href="website1.com">website1</a></td>
    <td>info1</td>
    <td>info2</td>              
    <td><a href="spam1.com">spam1</a></td>
</tr>
<tr>
    <td><a href="website2.com">website2</a></td>
    <td>info1</td>
    <td>info2</td>              
    <td><a href="spam2.com">spam2</a></td>
</tr>

我如何使用lxml在没有垃圾邮件的情况下,用信息1和信息2抓取网站并得到以下结果?在

^{pr2}$

Tags: com信息编程lxmltrtdhref初学者
3条回答
import lxml.html as LH

doc = LH.fromstring(content)
print([tr.xpath('td[1]/a/@href | td[position()=2 or position()=3]/text()')
       for tr in doc.xpath('//tr')])

长XPath具有以下含义:

^{pr2}$
import lxml.html as lh

tree = lh.fromstring(your_html)

result = []
for row in tree.xpath("tr"):
    url, info1, info2 = row.xpath("td")[:3]
    result.append([url.xpath("a")[0].attrib['href'],
                   info1.text_content(),
                   info2.text_content()])

结果:

^{pr2}$

我使用xpath:td/a[not(contains(.,"spam"))]/@href | td[not(a)]/text()

$ python3
>>> import lxml.html
>>> doc = lxml.html.parse('data.xml')
>>> [[j for j in i.xpath('td/a[not(contains(.,"spam"))]/@href | td[not(a)]/text()')] for i in doc.xpath('//tr')]
[['website1.com', 'info1', 'info2'], ['website2.com', 'info1', 'info2']]

相关问题 更多 >

    热门问题