很难输出多行,xPath问题?

2024-04-26 09:25:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试让Scrapy从论坛https://bitcointalk.org/index.php?topic=1209137.0中提取作者、日期和帖子,并将其导入到我的项目中。你知道吗

我想要的结果是:(使用我稍后将清理的无关html)

作者1,日期1,职位1

作者2,日期2,职位2

但我得到的却是: 作者1,2,3,4日期1,2,3,4,职位1,2,3,4

我四处搜索并阅读了一些关于将xpath从绝对值更改为相对值的内容,但似乎无法使其正常工作。我不确定这是根本原因,还是需要创建一个管道来转换数据?你知道吗

**********更新**********附加代码*************************

class Bitorg(scrapy.Spider):
name = "bitorg"
allowed_domains = ["bitcointalk.org"]
start_urls = [
    "https://bitcointalk.org/index.php?topic=1209137.0"
]

def parse(self, response):
    for sel in response.xpath('..//html/body'):
        item = BitorgItem()
        item['author'] = sel.xpath('.//b/a[@title]').extract()
        item['date'] = sel.xpath('.//td[@valign="middle"]/div[@class="smalltext"]').extract()
        item['post'] = sel.xpath('.//div[@class="post"]').extract()
        yield item

Tags: httpsorgtopicindexresponsehtml职位extract
2条回答

虽然<table><tbody><tr>元素没有可以轻松选择的属性,但是每个post都有一个<td>poster_info。你知道吗

要获得所有文章的列表,请在<td>上选择,并使用xpath ..符号向上移动树。你知道吗

posts = response.xpath('//*[@class="poster_info"]/..')

在每个帖子中,选择感兴趣的子元素。你知道吗

for post in posts:
    author = ''.join(post.xpath('.//td[@class="poster_info"]/.//b/a/.//text()').extract())
    title = ''.join(post.xpath('.//div[@class="subject"]/.//a/.//text()').extract())
    date = ''.join(post.xpath('.//div[@class="subject"]/following-sibling::div/.//text()').extract())

    print '%s, %s, %s' % (author, title, date)

你知道所有的代码只是一个大div里面有一个小表 以及作者的XPath

/html/body/div[2]/form/table[1]/tbody/tr[1]/td/table/tbody/tr/td/table/tbody/tr[1]/td[1]/b/a
/html/body/div[2]/form/table[1]/tbody/tr[5]/td/table/tbody/tr/td/table/tbody/tr[1]/td[1]/b/a
/html/body/div[2]/form/table[1]/tbody/tr[6]/td/table/tbody/tr/td/table/tbody/tr[1]/td[1]/b/a

你可以用这个刮东西

l = XPathItemLoader(item = JustDialItem(),response = response)
for i in range(1,10):
        l.add_xpath('content1','//*[@id="bodyarea"]/form/table[1]/tbody/tr['+str(i)+']/td/table/tbody/tr/td/table/tbody/tr[1]/td[1]/b/a/text()')
        l.add_xpath('content2','//*[@id="bodyarea"]/form/table[1]/tbody/tr['+str(i)+']/td/table/tbody/tr/td/table/tbody/tr[1]/td[1]/b/a/text()')
        l.add_xpath('content3','//*[@id="bodyarea"]/form/table[1]/tbody/tr['+str(i)+']/td/table/tbody/tr/td/table/tbody/tr[1]/td[1]/b/a/text()')

同样的方法,你也可以做的日期和职位

相关问题 更多 >