Joe*_*ndo 0 python xpath scrapy scraper
因此,我对使用 XPath 还比较陌生,而且我在磨练我需要用于我的特定应用程序的确切语法方面遇到了一些困难。我构建的刮板工作得非常好(当我使用不太复杂的路径时,它可以工作)。一旦我尝试更具体地了解我的路径,它就不会返回正确的值。
我试图操纵的文档结构的简化模型是
<table class="rightLinks">
<tbody>
<tr>
<td>
<a href="http://wwww.example.com">Text That I want to Grab</a>
</td>
<td>Some</td>
<td>Text</td>
</tr>
<tr>
<td>
<a href="http://wwww.example2.com">Text That I want to Grab</a>
</td>
<td>Some</td>
<td>Text</td>
</tr>
<tr>
<td>
<a href="http://wwww.example3.com">Text That I want to Grab</a>
</td>
<td>Some</td>
<td>Text</td>
</tr>
<tr>
<td>
<a href="http://wwww.example4.com">Text That I want to Grab</a>
</td>
<td>Some</td>
<td>Text</td>
</tr>
</tbody>
</table>
Run Code Online (Sandbox Code Playgroud)
基本上,我想获取 href 值和带有链接的文本。
这是我的刮板关于这个以及我迄今为止尝试过的部分:
import scrapy
from scrapy.selector import HtmlXPathSelector
from scrapy.http import HtmlResponse
def parse(self, response):
for sel in response.xpath('//table[@class="rightLinks"]/tbody/tr/*[1]/a'):
item = DanishItem()
item['company_name'] = sel.xpath('/text()').extract()
item['website'] = sel.xpath('/@href').extract()
yield item
Run Code Online (Sandbox Code Playgroud)
编辑:我正在使用的新路径
def parse(self, response):
for sel in response.xpath('//table[@class="rightLinks"]/tr/*[1]/a'):
item = DanishItem()
item['company_name'] = sel.text
item['website'] = sel.attrib['href']
yield item
Run Code Online (Sandbox Code Playgroud)
最终编辑:工作代码(谢谢大家!)
def parse(self, response):
for sel in response.xpath('//table[@class="rightLinks"]/tr/*[1]/a'):
item = DanishItem()
item['company_name'] = sel.xpath('./text()').extract()
item['website'] = sel.xpath('./@href').extract()
yield item
Run Code Online (Sandbox Code Playgroud)
任何建议或提示将不胜感激!
乔伊
sel.xpath('/text()')并且sel.xpath('/@href')都是绝对路径;如果你想要相对路径,这将是./text()or ./@href。
如果这是 lxml —— 并且sel是一个 lxmlElement对象 —— 只需使用sel.text,或者sel.attrib['href']—— 不需要 XPath。