【问题标题】:Scrapy, scraping elements only visible during runtimeScrapy,抓取元素仅在运行时可见
【发布时间】:2021-01-11 06:13:01
【问题描述】:

我是 Scrapy、HTML 和 Javascript 的新手。我正在尝试从网站上为我们的代理机构获取所有分支机构和代理的列表。我需要的大部分信息都可以从 AJAX 结果中提取:www.tysonprop.co.za/ajax/agents/?branch_id=[id]

挑战有两个方面:

  1. 网站上显示的分支名称 (https://www.tysonprop.co.za/agents/) 包含在查看页面源时不可见的 span 元素中。这意味着 Scrapy 无法找到信息。例如,“Tyson Properties Fourways Office”理论上应该位于:xpath(//div[@id="select2-result-label-76"]/span[@class="select2-match"]/text( )) [![查看检查元素][1]][1])

  2. AJAX 调用需要分支 ID。我无法弄清楚页面如何将下拉列表中选择的分支名称转换为分支 id 以拦截逻辑。 IE。如何提取具有相应 ID 的分支名称列表?

我进行了广泛的网络搜索,但没有取得多大成功。任何帮助,将不胜感激。 [1]:https://i.stack.imgur.com/1kjk8.png

class TysonSpider(scrapy.Spider):
    name = 'tyson_spider'

    def start_requests(self):
        url = 'https://www.tysonprop.co.za/ajax/agents/?branch_id=25'
        yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):

        agent = Agent()

        json_data = json.loads(response.text)

        branch_id = json_data['branch']['id']
        branch_name = json_data['branch']['branch_name']
        branch_tel = json_data['branch']['get_dialable_telephone_number']

        # Loop through all of th agents
        agent_list = json_data['agents']

        for key in range(len(agent_list)):
            agent['id'] = agent_list[key]['id']
            agent['branch_id'] = branch_id
            agent['branch_name'] = branch_name
            agent['branch_tel'] = branch_tel
            agent['privy_seal_url'] = agent_list[key]['privy_seal_url']

相关问题:Scrapy xpath not extracting div containing special characters <%=

【问题讨论】:

    标签: javascript python html scrapy


    【解决方案1】:

    如果您查看页面源代码,您可以看到分支 ID 和名称存在于 HTML 中,并且位于“name="agent_search"”下。 使用下面的逻辑,您可以遍历不同的分支并获取它们的 id 和名称:

    branches_xpath = response.xpath('//*[@name="agent_search"]//option')
    for branch_xpath in branches_xpath[1:]:  # skip first option as that one is empty
      branch_id = branch_xpath.xpath('./@value').get()
      branch_name = branch_xpath.xpath('./text()').get()
      print(f"branch_id: {branch_id}, branch_name: {branch_name}")
    
    

    【讨论】:

    • 谢谢 Wim,我错过了。还在学习!感谢帮助
    猜你喜欢
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-20
    • 1970-01-01
    • 2021-12-17
    • 2022-11-25
    相关资源
    最近更新 更多