小白教程

 找回密码
 立即注册
查看: 5817|回复: 2

需要帮助与 lxml.html 和 xpath

[复制链接]

1

主题

1

帖子

3

积分

新手上路

Rank: 1

积分
3
发表于 2021-2-23 09:42:38 | 显示全部楼层 |阅读模式
  1. data = response.text
  2. tree = html.fromstring(data)
  3. Services_Product = tree.xpath("//dt[text()='Services/Products']/following-sibling::dd[1]")
复制代码
这需要更多的工作。这个领域是
  1. file = open('html_01.txt', 'r')
  2. data = file.read()
  3. tree = html.fromstring(data)
  4. Services_Product = tree.xpath("//dt[text()='Services/Products']/following-sibling::dd[1]")
  5. stuff = Services_Product[0].xpath("//li")
  6. for elem in stuff:
  7.     print(elem[0][0].text)
复制代码


回复

使用道具 举报

2

主题

6

帖子

14

积分

新手上路

Rank: 1

积分
14
发表于 2021-2-25 10:36:41 | 显示全部楼层
可以用作BS的解析器,我总是这样做。
  1. soup = BeautifulSoup(response.content, 'lxml')
复制代码
  1. from lxml import html
  2. import requests


  3. resonse = requests.get(url)
  4. tree = html.fromstring(resonse.content)
  5. prod = tree.xpath('//*[@id="business-info"]/dl/dd[3]/ul')
  6. for tag in prod[0].getchildren():
  7.     print(tag.text)
复制代码
回复

使用道具 举报

0

主题

2

帖子

3

积分

新手上路

Rank: 1

积分
3
发表于 2021-3-16 15:36:46 | 显示全部楼层
当使用不同的标签并希望从该文本时,在已找到的部分上使用html2文本更容易
  1. import html2text

  2. data = '''\
  3. <dd>
  4.   A block of text here.... bla bla bla....
  5.   <ul>
  6.     <li><p>Item 1.  for some reason they wraped this in a p</p></li>
  7.     <li><strong>And this item is important</strong>bla bla bla</li>
  8.     <li>And just more info here...</li>
  9.   </ul>
  10.   And finally more stuff here...
  11. </dd>'''

  12. text = html2text.HTML2Text()
  13. text.mark_code = True
  14. text.ignore_emphasis = True
  15. text.single_line_break = True
  16. text.ignore_links = True
  17. text = text.handle(data)
  18. print(text.strip())
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|小白教程 ( 粤ICP备20019910号 )

GMT+8, 2024-9-20 14:45 , Processed in 0.037674 second(s), 26 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc. Template By 【未来科技】【 www.wekei.cn 】

快速回复 返回顶部 返回列表