Selenium+requests出现窗口不能跳转的情况

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40584718/article/details/85609518

用selenium+requests进行央视网新闻抓取的时候,会出现搜索页面无法跳转的情况。


爬虫设计的思路:

def search()#主要用来打开网页,并输入关键字进行搜索
def get_link_url()#定义抓取链接
def parse_html(link_url):#link_url是个列表,解析每一个链接得到的网页(requests.get())
def get_content(link):#link是个网址的列表,最后得到每一页的内容
def next_page():#定义翻页
def main()

爬虫在新闻搜索页面无法跳转:
可以通过:

driver.currunt_url()#driver=webdriver.Firefox()
In [203]: driver.current_url #还是之前的网址,并没有更新
Out[203]: 'http://www.cctv.com/'

In [204]: driver.current_window_handle#当前位置
Out[204]: '6442450945'

In [205]: driver.window_handles#共有多少个窗口
Out[205]: ['6442450945'] ['6442450949']

多了一个,说明搜索成功了,只是没有跳转.

通常可以通过以下方法解决:

 driver.forward()#表示前进
 driver.switch_to_window()#表示跳转

本文主要采用后者来解决search()的跳转问题。代码如下:

driver = webdriver.Firefox()
wait = WebDriverWait(driver, 10)

def search():
    print('正在搜索')
    try:
        driver.get('http://www.cctv.com/')#初始网址
        input = wait.until(
            EC.presence_of_element_located((By.XPATH, '//span//input[@class="input_txt2"]')))
        input.clear()
        input.send_keys("互联网+")#输入关键字
        submit = wait.until(
            EC.element_to_be_clickable((By.XPATH, '//span//input[@type="button"]')))
        submit.click()
        driver.execute_script('window.scrollTo(0,"document.body.scrollHeight")')
        #跳转到新的窗口
        if driver.current_window_handle==driver.window_handles[-1]:
            driver.execute_script('window.scrollTo(0,"document.body.scrollHeight")')
            print("已经自己跳转到新窗口",driver.current_url)  
        else:
            driver.switch_to_window(driver.window_handles[-1])
            driver.execute_script('window.scrollTo(0,"document.body.scrollHeight")')
            print("手工跳转",driver.current_url)
        return driver.current_url
    except TimeoutException:
        return search()

其中:

if driver.current_window_handle==driver.window_handles[-1]:
            driver.execute_script('window.scrollTo(0,"document.body.scrollHeight")')#向下滚动
            print("已经自己跳转到新窗口",driver.current_url)  
        else:
            driver.switch_to_window(driver.window_handles[-1])#认为最后一个就是搜索得到的窗口
            driver.execute_script('window.scrollTo(0,"document.body.scrollHeight")')
            print("手工跳转",driver.current_url)`
   可以执行跳转,但是会出现switch_to_window的弃用警告(***暂时可以忽略***)。

还有个问题没有解决:为什么50页以后的数据都是重复,是不是需要登录?需要进一步尝试,也有可能网页本身就是那样子。


欢迎进行爬虫交流

参考
崔庆才;课时1-3的代码

猜你喜欢

转载自blog.csdn.net/qq_40584718/article/details/85609518