Python 使用Scrapy和XPath解析表中的信息
我正在尝试使用scrapy和xpath从网站中提取属性:Python 使用Scrapy和XPath解析表中的信息,python,xpath,scrapy,Python,Xpath,Scrapy,我正在尝试使用scrapy和xpath从网站中提取属性: response.xpath('//section[@id="attributes"]/div/table/tbody/tr/td/text()').extract() 属性按以下方式嵌套: <section id="attributes"> <h5>Attributes</h5> <div> <table> <tbody&
response.xpath('//section[@id="attributes"]/div/table/tbody/tr/td/text()').extract()
属性按以下方式嵌套:
<section id="attributes">
<h5>Attributes</h5>
<div>
<table>
<tbody>
<tr>
<td>Attribute 1</td>
<td>Value 1</td>
</tr>
<tr>
<td>Attriburte 2</td>
<td>Value 2</td>
</tr>
属性
属性1
值1
属性2
价值2
与此相关的问题有两个:
td
,我需要以某种方式获得配对。e、 g.:“属性1”=“值1”for row in response.css('section#attributes table tr'):
td1 = row.xpath('.//td[1]/text()').get()
td2 = row.xpath('.//td[2]/text()').get()
# your logic further
首先,您应该尝试从XPath中删除
tbody
标记,因为它通常不在页面源代码中
您可以按如下方式更新代码:
cells = response.xpath('//section[@id="attributes"]/div/table//tr/td/text()').extract()
att_values = [{first: second} for first, second in zip(cells[::2], cells[1::2])]
您将获得属性值对列表:
[{attr_1: value_1}, {attr_2: value_2}, {attr_3: value_3}, ...]
或
查字典
{attr_1: value_1, attr_2: value_2, attr_3: value_3, ...}
谢谢,效果很好。虽然我不明白生成字典的att_values=行。@merlin,假设我们有list
l=[a',1',b',2',c',3]
zip(l[::2],l[1::2])
为我们生成元组('a',1),('b',2),('c',3)
[::2]
表示给我们列表中的所有偶数元素,[1::2]
-给我们所有奇数元素。我们只是从每个元组的2个值中生成键值:{'a':1,'b':2,'c':3}
{attr_1: value_1, attr_2: value_2, attr_3: value_3, ...}