【问题标题】:Problem Scraping Element & Child Text with lxml & etree使用 lxml 和 etree 抓取元素和子文本的问题
【发布时间】:2019-06-27 05:01:14
【问题描述】:

我正在尝试以特定格式从 Wikipedia 页面(例如:https://de.wikipedia.org/wiki/Liste_der_Bisch%C3%B6fe_von_Sk%C3%A1lholt)中抓取列表。我遇到了让 'li' 和 'a href' 匹配的问题。

例如,从上面的页面,第九个项目符号有文字:

1238–1268:Sigvarður Þéttmarsson(挪威)

使用 HTML:

 <li>1238–1268: <a href="/wiki/Sigvar%C3%B0ur_%C3%9E%C3%A9ttmarsson" title="Sigvarður Þéttmarsson">Sigvarður Þéttmarsson</a> (Norweger)</li>

我想把它拼成一本字典:

'1238–1268: Sigvarður Þéttmarsson(挪威)': '/wiki/Sigvar%C3%B0ur_%C3%9E%C3%A9ttmarsson'

['li' 和 'a' child 两个部分的全部文本]: ['a' child 的href]

我知道我可以使用 lxml/etree 来做到这一点,但我不完全确定如何。下面的一些重组?

from lxml import etree
tree = etree.HTML(html)

bishops = tree.cssselect('li').text for bishop
text = [li.text for li in bishops]

links = tree.cssselect('li a')
hrefs = [bishop.get('href') for bishop in links]

【问题讨论】:

    标签: python web-scraping css-selectors lxml elementtree


    【解决方案1】:

    更新:我使用 BeautifulSoup 解决了这个问题,如下所示:

     from bs4 import BeautifulSoup
    
     html = driver.page_source
     soup = BeautifulSoup(html, 'html.parser')
    
     bishops_with_links = {}
     bishops = soup.select('li')
    
     for bishop in bishops:
         if bishop.findChildren('a'):
             bishops_with_links[bishop.text] = 'https://de.wikipedia.org' + bishop.a.get('href')
         else:
             bishops_with_links[bishop.text] = ''
     return bishops_with_links
    

    【讨论】:

      猜你喜欢
      • 2014-07-27
      • 2019-03-11
      • 1970-01-01
      • 2015-09-10
      • 1970-01-01
      • 2016-04-03
      • 2014-11-24
      • 2011-11-18
      • 1970-01-01
      相关资源
      最近更新 更多