python - Xpath从具有样式属性的父标签解析子标签时出现问题

标签 python xpath lxml

以下是 html 内容的片段:

<div class="post-inner wow bounceInUp animated" data-wow-offset='80' data-wow-delay="0s" data-wow-duration="0.8s">
   <a href="https://url.com/hello/" class="post-link"></a>
   <div class="post-pic lazyload" data-bg="https://url.com/wp-content/uploads/2019/01/opioid-300x200.jpg" *style="background-image: url('');" * /></div>
   <div class="tags-wrapper">
      <a href="/tag/hello-world">Hello World</a>
      <a href="/tag/noob">Noob</a>
   </div>
   <h3>
      <a href="https://url.com/hello/">
      My First Title-Hello</a>
   </h3>
</div>

我正在尝试提取 h3 内的标题和链接。 我正在做的是:

>>> from lxml.html import fromstring
>>> content = """
<div class="post-inner wow bounceInUp animated" data-wow-offset='80' data-wow-delay="0s" data-wow-duration="0.8s">
...    <a href="https://url.com/hello/" class="post-link"></a>
...    <div class="post-pic lazyload" data-bg="https://url.com/wp-content/uploads/2019/01/opioid-300x200.jpg" *style="background-image: url('');" * /></div
>
...    <div class="tags-wrapper">
...       <a href="/tag/hello-world">Hello World</a>
...       <a href="/tag/noob">Noob</a>
...    </div>
...    <h3>
...       <a href="https://url.com/hello/">
...       My First Title-Hello</a>
...    </h3>
... </div>"""
>>> html_response = fromstring(content)
>>> main_tag = html_response.xpath('//div[@class="post-inner wow bounceInUp animated"]')
>>> main_tag
[<Element div at 0x106b347e0>]
>>> main_tag[0].xpath('div')
[<Element div at 0x106b34788>]
>>> main_tag[0].xpath('a')
[<Element a at 0x106b34838>]
>>> main_tag[0].xpath('a/@href')
['https://url.com/hello/']
>>> main_tag[0].xpath('h3/a')
[]
>>> main_tag[0].xpath('h3')
[]
>>> 

我无法在此处浏览 h3 标记。在排除故障时,如果我删除 *style="背景图像: url('');"*/

我能够提取标签。

有人可以帮我解决这个问题吗?

最佳答案

您要捕获的 div 在第三行末尾处关闭(请注意该行的第一个 div/> 结尾) 。因此,您要捕获的 h3 元素不在该 div 内。

关于python - Xpath从具有样式属性的父标签解析子标签时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54511776/

相关文章:

xml - 如何使用 XPath 选择以下兄弟/XML 标记

python - 将多行分组到新数据框中

python - 设置图例符号不透明度

python - PyBrain 多个目标值

XPath 包含多个值之一

python - 如何使用 Python 在多行文本中搜索 XPath 中的内容?

python - 两个 Pylons 记录器处理程序(Sentry/Raven 和控制台)用于相同的 qualname

python - 从元素/节点中提取 HTML

javascript - XPath 不适用于动态 HTML 文档

python - 从(相对)父文件夹导入 BeautifulSoup,并在其旁边导入一个 html 解析器