Scrapy / Splash单击一个按钮,然后在新窗口中从新页面获取内容

时间:2019-01-05 03:07:07

标签: python scrapy splash scrapy-splash

我遇到的问题是,当我单击按钮时,Javascript会处理该操作,然后将其重定向到带有新窗口的新页面(这与您以目标{{1单击<a> }})。在scrapy / splash中,我不知道如何从新页面获取内容(我的意思是我不知道如何控制该新页面)。

任何人都可以帮助您!

_Blank

1 个答案:

答案 0 :(得分:1)

问题:

您无法抓取超出选择范围的html的问题。单击新链接后,如果涉及到一个iframe,则很少将其纳入抓取范围。

解决方案:

选择一种选择新iframe的方法,然后继续解析新html。

Scrapy-Splash方法

(这是来自this answer的Mikhail Korobov解决方案的改编)

如果您能够获得弹出的新页面的src链接,则它可能是最可靠的,但是,您也可以尝试以这种方式选择iframe:

# ...
    yield SplashRequest(url, self.parse_result, endpoint='render.json', 
                        args={'html': 1, 'iframes': 1})

def parse_result(self, response):
    iframe_html = response.data['childFrames'][0]['html']
    sel = parsel.Selector(iframe_html)
    item = {
        'my_field': sel.xpath(...),
        # ...  
    }

硒方法

(需要pip install selenium,bs4,可能还需要从此处为您的操作系统下载chrome驱动程序:Selenium Chromedrivers)支持Javascript解析!哇!

使用以下代码,这会将范围切换到新框架:

# Goes at the top
from bs4 import BeautifulSoup 
from selenium.webdriver.chrome.options import Options
import time

# Your path depends on where you downloaded/located your chromedriver.exe
CHROME_PATH = 'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'
CHROMEDRIVER_PATH = 'chromedriver.exe'
WINDOW_SIZE = "1920,1080"

chrome_options = Options()
chrome_options.add_argument("--log-level=3")
chrome_options.add_argument("--headless") # Speeds things up if you don't need gui
chrome_options.add_argument("--window-size=%s" % WINDOW_SIZE)

chrome_options.binary_location = CHROME_PATH

browser = webdriver.Chrome(executable_path=CHROMEDRIVER_PATH, chrome_options=chrome_options)

url = "example_js_site.com" # Your site goes here
browser.get(url)
time.sleep(3) # An unsophisticated way to wait for the new page to load.
browser.switch_to.frame(0)

soup = BeautifulSoup(browser.page_source.encode('utf-8').strip(), 'lxml')

# This will return any content found in tags called '<table>'
table = soup.find_all('table') 

这两个选项中我最喜欢的是Selenium,但如果您更喜欢它,请尝试第一种解决方案!

相关问题