Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如果花费的时间太长,请跳过selenium Webdriver.get()对循环的内部调用_Python_Selenium_Loops - Fatal编程技术网

Python 如果花费的时间太长,请跳过selenium Webdriver.get()对循环的内部调用

Python 如果花费的时间太长,请跳过selenium Webdriver.get()对循环的内部调用,python,selenium,loops,Python,Selenium,Loops,嘿,伙计们,我很难理解如何将异常添加到for-in-range循环中。现在,我正在从excel工作表中提取URL,并在整个页面中移动时抓取信息,直到到达第200页。问题是并不是所有的URL都有多达200页的页面,所以在循环结束并且程序可以继续使用另一个URL之前需要花费很多时间。这里有没有实现代码异常的方法 从selenium导入webdriver 作为pd进口熊猫 导入时间 driver=webdriver.Chrome(“C:/Users/Acer/Desktop/chromedriver.

嘿,伙计们,我很难理解如何将异常添加到for-in-range循环中。现在,我正在从excel工作表中提取URL,并在整个页面中移动时抓取信息,直到到达第200页。问题是并不是所有的URL都有多达200页的页面,所以在循环结束并且程序可以继续使用另一个URL之前需要花费很多时间。这里有没有实现代码异常的方法

从selenium导入webdriver
作为pd进口熊猫
导入时间
driver=webdriver.Chrome(“C:/Users/Acer/Desktop/chromedriver.exe”)
公司=[]
df=pd.read\u excel('C:/Users/Acer/Desktop/url.xlsx')
对于索引,df.iterrows()中的行:
基本url=(第['url'行])
对于范围(1201,1)内的i:
url=“{base\u url}?curpage={i}”。格式(base\u url=base\u url,i=i)
获取驱动程序(url)
时间。睡眠(2)
name=driver。通过xpath('//a/div/div/p')查找元素
对于名称中的名称:
打印(名称、文本、url)
companys.append([names.text,url])
您可以在Webdriver上,然后观察循环中的
超时
异常:

from selenium.common.exceptions import TimeoutException

MAX_TIMEOUT_SECONDS = 5

driver = webdriver.Chrome("C:/Users/Acer/Desktop/chromedriver.exe")
driver.set_page_load_timeout(MAX_TIMEOUT_SECONDS)

for i in range(1, 201):
    try:
        url = "{base_url}?curpage={i}".format(base_url=base_url, i=i)
        driver.get(url)
    except TimeoutException:
        # skip this if it takes more than 5 seconds
        continue
    ... # process the scraped URL as usual

如果出现超时,则通过使用关键字
continue

跳过当前迭代。您可以跳过当前循环周期并从下一个循环开始。也许这能帮你解决问题