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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.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 当我自动打开网站时,如何避免连接错误?_Python_Selenium_Web Scraping_Debian_Python Requests - Fatal编程技术网

Python 当我自动打开网站时,如何避免连接错误?

Python 当我自动打开网站时,如何避免连接错误?,python,selenium,web-scraping,debian,python-requests,Python,Selenium,Web Scraping,Debian,Python Requests,我正在用Python2.7在Debian上浏览一些网站,但我的代码可能会自动停止(如果不能及时加载(冻结)或没有互联网连接) 有没有解决这个问题的方法,或者干脆跳过这个问题,把我的代码运行到下一个URL?因为如果我遇到这样的问题,这个脚本就会自动停止 这是我的代码: #!/usr/bin/python #!/bin/sh # -*- coding: utf-8 -*- from bs4 import BeautifulSoup from selenium import webdriver imp

我正在用Python2.7在Debian上浏览一些网站,但我的代码可能会自动停止(如果不能及时加载(冻结)或没有互联网连接)

有没有解决这个问题的方法,或者干脆跳过这个问题,把我的代码运行到下一个URL?因为如果我遇到这样的问题,这个脚本就会自动停止

这是我的代码:

#!/usr/bin/python
#!/bin/sh
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
from selenium import webdriver
import urllib2
import subprocess
import unicodecsv as csv
import os
import sys
import io
import time
import datetime
import pandas as pd
import MySQLdb
import re
import contextlib
import selenium.webdriver.support.ui as ui
import numpy as np
from datetime import datetime, timedelta
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By 
import pyautogui 
from pykeyboard import PyKeyboard

reload(sys)
sys.setdefaultencoding('utf-8')


cols = ['MYCOLS..'] 

browser = webdriver.Firefox()
datatable=[]

browser.get('LINK1')
time.sleep(5)

browser.find_element_by_xpath('//button[contains(text(), "CLICK EVENT")]').click()
time.sleep(5)
browser.find_element_by_xpath('//button[contains(text(), "CLICK EVENT")]').click()
html = browser.page_source
soup=BeautifulSoup(html,"html.parser")
table = soup.find('table', { "class" : "table table-condensed table-hover data-table m-n-t-15" })    

for record in table.find_all('tr', class_="hidden-xs hidden-sm ng-scope"):   
    for data in record.find_all("td"):
        temp_data.append(data.text.encode('utf-8'))
    newlist = filter(None, temp_data)
    datatable.append(newlist)
       
time.sleep(10) 
browser.close()

#HERE I INSERT MY DATAES INTO MYSQL..IT IS NOT IMPORTANT, AND MY SECOND LINK STARTING HERE

browser = webdriver.Firefox()
datatable=[]
   
browser.get('LINK2')
browser.find_element_by_xpath('//button[contains(text(), "LCLICK EVENT")]').click()
time.sleep(5)
html = browser.page_source
soup=BeautifulSoup(html,"html.parser")
table = soup.find('table', { "class" : "table table-condensed table-hover data-table m-n-t-15" })

for record in table.find_all('tr', class_="hidden-xs hidden-sm ng-scope"):   
    for data in record.find_all("td"):
        temp_data.append(data.text.encode('utf-8'))
    newlist = filter(None, temp_data)
    datatable.append(newlist)
       
time.sleep(10) 
browser.close()

#MYSQLDB PART AGAIN...AND THE NEXT LINK IS COMING.
+1编辑:


当脚本找不到此单击事件时,也停止。为什么?如何避免这种情况?

使用Selenium,您可以将驱动程序(浏览器对象)配置为等待特定的元素或条件。然后您可以使用常规的try/except来处理任何错误,例如
TimeoutException
或许多其他错误

Selenium很好地解释了等待系统

以下是Selenium上异常处理的代码片段:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

try:
    # Wait for any element / condition, you can even had lambda if you wish to
    WebDriverWait(browser, 10).until(
        EC.visibility_of_all_elements_located((By.ID, 'my-item'))
    )
except TimeoutException:
    # Here I raise an error but you can do whatever you want like exiting properly or logging something
    raise RuntimeError('No Internet connection')

因此,本页的最后一条评论对答案有一些提示:

显然,Nike使用akamai作为机器人保护器,迄今为止,它在阻止我们进入Nike的所有尝试方面表现出色:)我也通过下面的代码尝试了同样的尝试。请随时更新或评论任何解决方案。我会一直盯着这里

#为bud自动购买nike产品

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep as sl
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC 
import datetime as dt
#设置驱动程序的路径

PATH = 'C:\Program Files (x86)\chromedriver.exe'
#正在创建驱动程序的实例

driver = webdriver.Chrome(PATH)
#手动设置启动get请求的目标日期

tg_day = dt.datetime(2021, 5, 22, 1, 8, 30, 1)
print(tg_day)
#立即匹配()到目标日期,然后继续

def time_check():
date = dt.datetime.now()
print(date)

if tg_day.hour == date.hour and tg_day.minute == date.minute and tg_day.second == date.second:
    print("Activated")
    nike_website() # this breaks out of the while loop if it's the right day.

else:
    print("Waiting a bit longer....")
    sl(1) #wait 1 seconds

        
#驱动程序和可操作的方法

def nike_website():

driver.get('https://gs.nike.com/?checkoutId=c8195822-6539-4651-bfc7-eb8bf4156237&launchId=e18f55bb-c188-4fab-83c0-cc19107f59e7&skuId=28a2f06b-565d-5fc1-9dbd-6b1bfaf4acd3&country=IN&locale=en-GB&appId=com.nike.commerce.snkrs.web&returnUrl=https:%2F%2Fwww.nike.com%2Fin%2Flaunch%2Ft%2Flebron-18-low-mimi-plange-higher-learning%2F')
print(driver.title)

driver.switch_to.default_content()
wait = WebDriverWait(driver,10)
wait.until(EC.element_to_be_clickable((By.NAME, 'emailAddress')))
#对于添加的缓冲区睡眠5秒,也是冗余的是

sl(5)
#通过名称查找元素电子邮件

email = driver.find_element_by_name("emailAddress")
email.send_keys("<PUT YOUR EMAIL HERE>")
email.send_keys(Keys.RETURN)
password = driver.find_element_by_name("password")
password.send_keys("<PUT YOUR PASSWORD HERE>")
password.send_keys(Keys.RETURN)
#活化

while True:
time_check()

两件事,1。将代码建模器设为1。使用异常处理欢迎使用堆栈溢出!请参阅:SO的期望是,用户提问时不仅要进行研究以回答自己的问题,还要分享研究、代码尝试和结果。这表明你花了时间来帮助自己,它使我们避免重复显而易见的答案,最重要的是,它帮助你得到一个更具体和相关的答案!另请参见:例如,我可以等待按钮?这是示例网页:和我的代码:browser。通过xpath(“//按钮[contains(text(),“Load Early flights”)]”查找元素。单击(),我如何将其构建到我的代码中以及我必须放在哪里?我不会为你做任何事情,我给了你一个提示。现在使用Selenium,您可以轻松构建,只需查看他们的文档,我刚才用了一个正确的示例问他们..谢谢你。只需使用WebDriverWait(浏览器,10)。直到(EC.visibility_of_all_elements_位于((By.XPATH,'YOUR XPATH'))在try/except中。如果没有问题,那么你知道你可以得到你的元素
while True:
time_check()