pingfanren2 2021-03-23 14:38 采纳率: 80%
浏览 26
已采纳

python xpath对孙节点内容进行匹配问题

首先查看节点结构如下,需要获取节点summaryrecordstable下的所有后代节点中,具有数据值id=RECORD_[0-9]的节点

代码如下

  1. import requests
  2. from lxml import etree
  3. url_base='https://apps.webofknowledge.com'
  4. url_test='https://apps.webofknowledge.com/full_record.do?product=WOS&search_mode=GeneralSearch&qid=2&SID=6C4xx6Mer35kGYw4PU7&page=1&doc=50'
  5. url_head={
  6. 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36 Edg/89.0.774.57'
  7. }
  8. session=requests.session();
  9. res=session.get(url_test,headers=url_head)
  10. res_html = etree.HTML(res.text)
  11. url_cited_post=res_html.xpath('//a[@title="View all of the articles that cite this one"]/@href')#如果把@herf替换为text(),获取不到信息,因为a标签只有属性没有文本
  12. print(url_cited_post[0])
  13. url_allcited=url_base+url_cited_post[0]
  14. res=session.get(url_allcited,headers=url_head)
  15. res_html = etree.HTML(res.text)
  16. # url_cited_post=res_html.xpath('//div[contains(@id,"RECORD_")]')
  17. url_cited_post=res_html.xpath('//div[contains(@id,"summaryRecordsTable")]//div[contains(@id,"RECORD_")]')
  18. print('end')

倒数第三行,井号注释哪一行可以正常输出,但是加上前缀后,如倒数第二行,就不能正常输出了,不知道是怎么回事

 

展开全部

  • 写回答

1条回答 默认 最新

  • coagenth 2021-03-23 15:05
    关注

    用following定位,把前面设为顶节点,following后利用属性值再定位子孙节点。

    url_cited_post = res_html.xpath(

        './/div[contains(@id,"summaryRecordsTable")]//following::div[contains(@id,"RECORD_")]')

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部