我正在尝试将 scrapy 与 selenium 结合使用,以便能够与 javascript 交互,并且仍然拥有 scrapy 提供的强大的抓取框架。我写了一个访问的脚本http://www.iens.nl http://www.iens.nl,在搜索栏中输入“阿姆斯特丹”,然后点击搜索按钮成功。单击搜索按钮后,我希望 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()
“properties”是另一个脚本,如下所示:
from scrapy.item import Item, Field
class PropertiesItem(Item):
# Primary fields
description = Field()
Q:如何成功地使 scrapy 通过其在硒到达的页面上的 xpath 找到我称为“描述”的元素并将其作为输出返回?
提前致谢!
the response
您分配给您的对象ItemLoader
is the scrapy
响应,不是 Selenium 的。
我建议创建一个新的Selector
selenium 返回的页面源:
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
将从该响应结构而不是 scrapy 中获取信息(您实际上并不需要)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)