scrapy 在标记之间循环时出现XPATH问题

cnh2zyt3  于 2022-11-09  发布在  其他
关注(0)|答案(1)|浏览(147)

我有一段代码,我试图下载这些文件,但是循环只打印了第一个元素。
从urllib导入scrapy。解析导入urljoin
类简单蜘蛛(小蜘蛛):新冠肺炎病例报告网站首页

def parse(self, response):

    for book in response.xpath('//*[@id="main-content"]/div/main/div[2]/ol'):

        title= response.xpath('/li[3]/article/h3/a/text()').get()
        link = urljoin(
          'https://jmedicalcasereports.biomedcentral.com/',response.xpath('/li[3]/article/ul/li[2]/a/@href').get()
        )
        yield {
            'Title':title,
            'file_urls':[link]
        }

我使用了css,然后是xpath,问题是循环代码。

cngwdvgl

cngwdvgl1#

首先,在代码的第三行中,response可以更改为title

title= book.xpath('.//a/text()').get()

第二,在你的第二行,你给予了一个不正确的xpath。所以结果是不正确的。这是我的代码。希望这能帮助你。

def parse(self, response):
      for book in response.xpath('//li[@class = "c-listing__item"]'):
        title= book.xpath('.//a/text()').get()
        link = urljoin(
        'https://jmedicalcasereports.biomedcentral.com/',book.xpath('.//a/@href').get()
        )
        yield {
            'Title':title,
            'file_urls':[link]
        }

回应是:

{'Title': 'Presentation of COVID-19 infection with bizarre behavior and 
encephalopathy: a case report', 'file_urls': 
['https://jmedicalcasereports.biomedcentral.com/articles/10.1186/s13256-021- 
02851-0']}
2022-04-17 21:54:27 [scrapy.core.scraper] DEBUG: Scraped from <200 
https://jmedicalcasereports.biomedcentral.com/articles?query=COVID- 
19&searchType=journalSearch&tab=keyword>
{'Title': 'Dysentery as the only presentation of COVID-19 in a child: a\xa0case 
report', 'file_urls': 
['https://jmedicalcasereports.biomedcentral.com/articles/10.1186/s13256-021- 
02672-1']}

相关问题