【问题标题】:Adding str to every item in list python3将str添加到列表python3中的每个项目
【发布时间】:2020-08-03 10:06:23
【问题描述】:

简介

自从我开始熟悉scrapy,我尝试从随机网页中抓取一些链接。

问题

我保存到我的 items.py 文件的链接没有写:“https://”,但我需要它们作为超链接。

所以我想在实际链接之前添加“https://”,以便将其格式化为超链接。

我的代码

    def parse_target_page(self, response):
        card = response.xpath('//div[@class="text-center artikelbox"]')

        for a in card:
            items = LinkcollectItem()
            link = ('a/@href')
            items ['Title'] = a.xpath('.//h5[@class="title"]/a/text()').get()
            items ['Link'] = a.xpath('.//h5[@class="title"]/a/@href').get()
            yield items

我尝试在索引 0 处插入字符串,但没有成功

我的输出应该将所有链接打印为 csv 文件中的超链接。

【问题讨论】:

    标签: python-3.x list xpath web-scraping scrapy


    【解决方案1】:

    如果您只需要为每个链接添加https://,您可以执行以下操作:

    link = a.xpath('.//h5[@class="title"]/a/@href').get()
    items ['Link'] =  "https://" + link if link else link
    

    【讨论】:

    • 什么问题/错误?您在输出中看到了这些变化?
    • 很抱歉,它运行良好。我忘了 ”]”。谢谢先生!
    猜你喜欢
    • 2018-03-09
    • 2021-12-22
    • 2021-06-29
    • 2021-10-31
    • 1970-01-01
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多