【问题标题】:How can I extract text in a div and the hyperlink in it using scrapy?如何使用scrapy提取div中的文本和其中的超链接?
【发布时间】:2021-02-11 23:42:42
【问题描述】:

我正在使用 scrapy 从网站上抓取文本。我是scrapy和xpath的初学者。一些“div”标签包含一些文本,后跟一个链接,然后是一些文本。我想以相同的顺序提取文本和链接。

例如。

<div class="postbody">
    <blockquote>
       <div>
          <cite>Anonymous wrote:</cite>Daycares have been open for at least six months. Some never closed during the pandemic. They seem to be doing fine. 
          <br /> 
          <br /> Sorry, teachers. Vacation has to end sometime. 
        </div>
    </blockquote>
  <br /> 
  <br /> Nah, they're not doing fine.
  <br /> <a class="snap_shots" href="https://coronavirus.dc.gov/page/outbreak-data" target="_blank" rel="nofollow">https://coronavirus.dc.gov/page/outbreak-data</a>
  <br /> 
  <br /> /not a teacher
</div>

我只想要以下

Nah, they're not doing fine.
https://coronavirus.dc.gov/page/outbreak-data

/not a teacher

这是我到目前为止所做的。但它也会从不受欢迎的部分获取链接(如上例中的“blockquotes”标签)并将其附加到末尾。

post_text_response = post.xpath('.//div[@class="postbody"]/text()').getall()
post_link_attached = post.xpath('.//div[@class="postbody"]//a/@href')
post_text = re.sub(r'\s+', " ", "".join(post_text_response)).strip()             
if(len(post_link_attached)>0):
    post_text += " " + post_link_attached.extract_first()
  1. 如何在 scrapy 中使用 XPath 实现这一点?
  2. 虽然我的方法似乎可行,但在使用 xpath 时是否有更好的方法来忽略“blockquote”标签?

【问题讨论】:

    标签: python xpath scrapy


    【解决方案1】:

    您可以使用以下 XPath-1.0 表达式:

    //div[@class='postbody']/br/following-sibling::text()[1] | //div[@class='postbody']/br/following-sibling::a[1]/text()
    

    此表达式输出所有text() 节点或a/text() 节点之后的任何&lt;br&gt; 元素,该元素是&lt;div class="postbody"&gt; 的子元素。


    它的输出是

    Nah, they're not doing fine.
    https://coronavirus.dc.gov/page/outbreak-data 
    /not a teacher
    

    【讨论】:

      猜你喜欢
      • 2015-03-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-05
      • 1970-01-01
      相关资源
      最近更新 更多