使用 python 从网站中提取 link,scrapy 无法正常工作

Extracting link from a website using python, scrapy is not working

我想从“https://www.theknot.com/marketplace/bayside-bowl-portland-me-1031451”抓取网站 link,并且我使用了正确的 xpath 代码,即 response.xpath("//a[@title='website']/@href").get(),但是它在抓取时显示空结果。

一些网站(事实上,很多)使用Javascript来生成内容。这就是为什么您需要始终检查源 HTML 代码。

对于此页面,您会发现您需要的所有信息都在带有此文本 window.__INITIAL_STATE__ = script 标签内。您需要获取此文本,然后您可以使用 json 模块来解析它:

import scrapy
import json

class TheknotSpider(scrapy.Spider):

    name = 'theknot'
    start_urls = ['https://www.theknot.com/marketplace/bayside-bowl-portland-me-1031451']

    def parse(self, response):
        initial_state_raw = response.xpath('//script[contains(., "window.__INITIAL_STATE__ = ")]/text()').re_first(r'window\.__INITIAL_STATE__ = (\{.+?)$')
        # with open('Samples/TheKnot.json', 'w', encoding='utf-8') as f:
        #     f.write(initial_state_raw)
        initial_state = json.loads(initial_state_raw)
        website = initial_state['vendor']['vendor']['displayWebsiteUrl']
        print(website)