Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scrapy xpath-匹配DIV值,然后在匹配时提取或写入单独的字段_Xpath_Web Scraping_Scrapy - Fatal编程技术网

Scrapy xpath-匹配DIV值,然后在匹配时提取或写入单独的字段

Scrapy xpath-匹配DIV值,然后在匹配时提取或写入单独的字段,xpath,web-scraping,scrapy,Xpath,Web Scraping,Scrapy,我正在用Scrapy做一些事情,因为我是新手。我试图提取每个DIV值,并在写入CSV时将其存储在单独的列中。有时结构可能会改变,例如某些列表可能没有手机号码,或者可能有手机号码而没有电话号码等等,这意味着DIV将不存在于DOM中 如果我遍历结构,它将给出不一致的结果,因为某些DIV可能不在那里,因为数据插件不在那里。这可能意味着我映射了错误的数据 这是数据结构: <div id="business_contact_details"> <div class="contact_d

我正在用Scrapy做一些事情,因为我是新手。我试图提取每个DIV值,并在写入CSV时将其存储在单独的列中。有时结构可能会改变,例如某些列表可能没有手机号码,或者可能有手机号码而没有电话号码等等,这意味着DIV将不存在于DOM中

如果我遍历结构,它将给出不一致的结果,因为某些DIV可能不在那里,因为数据插件不在那里。这可能意味着我映射了错误的数据

这是数据结构:

<div id="business_contact_details">

<div class="contact_details">
 <strong>Contact Person:</strong>
 John Doe
</div><br clear="left"/>

<div class="contact_details">
 <img alt="" class="xfort alpha" src="/images/icons/phonenumber.png?f13g7f" title="phone" /> <strong>Phone:</strong>
 02 42223114
</div>

<div class="contact_details">
 <img alt="" class="xfort alpha" src="/images/icons/mobilenumber.png?sss2" title="phone" /> <strong>Mobile:</strong>
 0466156389
</div>
我一直在尝试使用这种格式
response.xpath(“//div[contains(@class,'contact_field'))]/genderant::strong[contains(text(),'Mobile:')]”)。extract()
,但只获取字符串而不是值

我尝试开发的逻辑是:例如:如果DIV=Mobile,则提取值。等等,这样我就可以将正确的值映射到列名。如果他们没有上传手机号码,那么这将是空的

另外,当我运行这个
response.xpath(“//div[contains(@class,'contact_details')]/text()”)时,extract()

在结果中我得到了很多:
['\n','\n John Doe\n','\n','\n','\n','\n','\n','\n','\n','\n','\n']
我怎样才能摆脱它


任何帮助都会很好

为了提取电话号码,我会使用如下xpath:

//img[@title="phone"]/parent::div/text()
或者只取一个特定的电话号码

//strong[text()="Phone:"]/parent::div/text()
要为名称提取创建一个不带空格的值,请执行以下操作:

u"".join(line.strip() for line in response.xpath("//div[contains(@class, 'contact_details')]/text()").extract())

如果您想从“手机:
div
获取电话号码,您可以尝试:

//div[./strong="Mobile:"]/text()

如果手机号码存在,则应返回手机号码或不返回任何内容

您是否也可以为
div
共享
HTML
,以获取空值?没有手机的div看起来怎么样?没有手机的div看起来很安全,没有手机的div看起来像:
联系人:
电话:02 42223114
div就不会出现了
//div[./strong="Mobile:"]/text()