【发布时间】:2015-04-03 14:57:44
【问题描述】:
我正在尝试使用 Scrapy 抓取电影列表(我只获取导演和电影标题字段)。 有时,有两个导演,Scrapy 认为他们是不同的。所以第一个导演只有电影片名,而第二个导演没有电影片名。
所以我创造了一个这样的条件:
if director2:
item['director'] = map(unicode.strip,titres.xpath("tbody/tr/td/div/div[2]/div[3]/div[2]/div/h2/div/a/text()").extract())
最后一个 div[2] 只有在有两个导演时才存在。
我想像这样连接:director1,director2
这是我的完整代码:
class movies(scrapy.Spider):
name ="movielist"
allowed_domains = ["domain.com"]
start_urls = ["http://www.domain.com/list"]
def parse(self, response):
for titles in response.xpath('//*[contains(concat(" ", normalize-space(@class), " "), " grid")]'):
item = MovieItem()
director2 = Selector(text=html_content).xpath("h2/div[2]/a/text()")
if director2:
item['director'] = map(unicode.strip,titres.xpath,string-join("h2//concat(div[1]/a/text(), ".", div[2]/a/text())").extract())
else:
item['director'] = map(unicode.strip,titres.xpath("h2/div/a/text()").extract())
item['director'] = map(unicode.strip,titres.xpath,string-join("h2//concat(div[1]/a/text(), ".", div[2]/a/text())").extract())
item['title'] = map(unicode.strip,titres.xpath("h2/a/text()").extract())
yield item
一个导演的 HTML 示例:
<h2>
<a href="#">Movie's title</a>
<div>Info</div>
<div><a href="#">Director's name</a></div>
</h2>
有时候,当有两个导演时:
<h2>
<a href="#">Movie's title</a>
<div>Info</div>
<div><a href="#">Director's name</a></div>
<div><a href="#">Second director's name</a></div>
</h2>
你能告诉我我的语法有什么问题吗?
我在没有条件和没有连接的情况下进行了测试,效果很好。
这是我第一次接触 Python,所以请多多包涵。
非常感谢。
【问题讨论】:
-
请添加示例 HTML 输入,通过逆向思考您的 XPath 很难想象内容
-
@paultrmbrth 哦,抱歉,我添加了一个示例 HTML 输入,我减少了我的 xpath 只是为了示例,因为我真正的问题在于语法。
标签: python xpath web-crawler scrapy