python爬虫 针对带有高亮span标签的文本提取xpath语法

python爬虫 针对带有高亮span标签的文本提取xpath语法

问题描述:

本人刚刚入门爬虫,打算爬取学术论文网站上的论文信息。在我搜索关键词之后的结果列表中,关键词都被高亮显示了,对应的html文件中是span标签,此标签把论文的文章名字分割开了,导致我不能用xpath语句完整的提取整个文章名的text,像这种情况我该如何解决?

这是该元素对应的html语句:

    
    <a href="/doi/10.1002/9783527635245.ch4" class="publication_title visitable">Fundamentals of <span onclick="highlight()" class="single_highlight_class">Image</span> Processing</a>.

这是脚本文件中的xpath语句:

 parser = etree.HTMLParser(encoding="utf-8")
 tree = etree.parse(save_path, parser=parser)

 site_list = tree.xpath(
     '//*[@id="search-result"]/li[@class="clearfix search__item separator bulkDownloadWrapper"]/div/h2/span/a/@href')
 article_name_list = tree.xpath(
     '//*[@id="search-result"]/li[@class="clearfix search__item separator bulkDownloadWrapper"]/div/h2/span/a/text() '
     '| //*[@id="search-result"]/li[@class="clearfix search__item separator bulkDownloadWrapper"]/div/h2/span/a/span/text()')

 name_site_dict = dict(zip(article_name_list, site_list))
 with open('articles_wiley.json', 'w') as f:
     json.dump(name_site_dict, f)

正常运行之后存入json文件中的内容是这样:

{"Fundamentals of ": "https://onlinelibrary.wiley.com/doi/10.1002/9783527635245.ch4", 
  "Image": "https://onlinelibrary.wiley.com/doi/10.1002/9781118093467.ch5", 
  " Processing": "https://onlinelibrary.wiley.com/doi/10.1002/0471219282.eot221",  ...}

我想达到的效果是整个文章名称对应该文章的链接,像这样:

{"Fundamentals of Image Processing": "https://onlinelibrary.wiley.com/doi/10.1002/9783527635245.ch4", 
  "下一个文章名": "https://onlinelibrary.wiley.com/doi/10.1002/9781118093467.ch5", 
  "下一个文章名": "https://onlinelibrary.wiley.com/doi/10.1002/0471219282.eot221",  ...}

想请问各位针对这种情况,有没有对应的xpath语句直接提取完整的text?
同时也要考虑,如果某一条文章名种没有高亮(可能存在于文章概述种),该语句也同样适用吗?
如果转化成字符串处理的话,如何跟取出的网址列表的元素一一对应呢?
感谢各位解答!!

 还有一个问题,json文件可以用python转成bib文件格式吗?或者通过上边的方法可不可提取出类似bib文件的格式信息呢?


 article_name_list = tree.xpath( '//*[@id="search-result"]/li[@class="clearfix search__item separator bulkDownloadWrapper"]/div/h2/span/a')
print(article_name_list.text)

试试直接定位a标签,然后调用text取值