使用硒+肉末

2024-06-28 20:21:00 发布

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

我尝试使用scrapy和selenium来与javascript交互,同时仍然拥有scrapy提供的强大的scraping框架。我写了一个脚本,访问http://www.iens.nl,在搜索栏中输入“Amsterdam”,然后成功地单击搜索按钮。在点击搜索按钮之后,我想让scrapy从新呈现的页面中检索一个元素。不幸的是,scrapy没有返回任何值。在

我的代码是这样的:

from selenium import webdriver
from scrapy.loader import ItemLoader
from scrapy import Request
from scrapy.crawler import CrawlerProcess
from properties import PropertiesItem
import scrapy


class BasicSpider(scrapy.Spider):
    name = "basic"
    allowed_domains = ["web"]
    # Start on a property page
    start_urls = ['http://www.iens.nl']

    def __init__(self):
        chrome_path = '/Users/username/Documents/chromedriver'
        self.driver = webdriver.Chrome(chrome_path)

    def parse(self, response):
        self.driver.get(response.url)
        text_box = self.driver.find_element_by_xpath('//*[@id="searchText"]')
        submit_button = self.driver.find_element_by_xpath('//*[@id="button_search"]')
        text_box.send_keys("Amsterdam")
        submit_button.click()

        l = ItemLoader(item=PropertiesItem(), response=response)
        l.add_xpath('description', '//*[@id="results"]/ul/li[1]/div[2]/h3/a/')

        return l.load_item()


process = CrawlerProcess()
process.crawl(BasicSpider)
process.start()

“属性”是另一个类似的脚本:

^{pr2}$

Q:如何成功地让scrapy在selenium reached页面上通过xpath找到我称为“description”的元素并将其作为输出返回?在

提前谢谢!在


Tags: fromimportself脚本idhttpresponsewww
1条回答
网友
1楼 · 发布于 2024-06-28 20:21:00

您分配给您的response对象是scrapy响应,而不是Selenium的

我建议使用selenium返回的页面源创建一个新的Selector

from scrapy import Selector
...

selenium_response_text = driver.page_source

new_selector = Selector(text=selenium_response_text)
l = ItemLoader(item=PropertiesItem(), selector=new_selector)
...

这样,add_xpath将从该响应结构中获取信息,而不是垃圾信息(实际上您并不需要这些信息)。在

相关问题 更多 >