为什么插座会干扰硒?

2024-06-10 19:32:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个python脚本,使用socket(Checking network connection)检查internet连接,然后使用selenium从YahooFinance获取html。在

它经常(但不总是)给出ReadTimeoutError(见下文)

我可以通过使用http.客户端相反(见下文),但我仍然想知道为什么插座会干扰硒。在


def internet(host="8.8.8.8", port=443, timeout=1):
    try:
        socket.setdefaulttimeout(timeout)
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((host, port))
        s.shutdown(socket.SHUT_RDWR)
        s.close()
        return True
    except OSError:  
        s.close()
        return False

#  Wait for internet to be available

i = 1
while internet() is False:
    time.sleep(1)
    if i == 300:  # quit if no connection for 5 min (300 seconds)
        print('\nIt has been 5 minutes. Aborting attempt.\n')
        sys.exit(0)
    i += 1

# Get html from yahoo page

symb = 'AAPL'
url = 'http://finance.yahoo.com/quote/{}/history'.format(symb)

chop = webdriver.ChromeOptions()
chop.add_argument('--user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:68.0) Gecko/20100101 Firefox/68.0"')
driver = webdriver.Chrome('/Users/fake_user/Dropbox/Python/chromedriver', chrome_options=chop)
driver.get(url)
html_source = driver.page_source
driver.quit()

它抛出以下错误:

urllib3.exceptions.ReadTimeoutError: HTTPConnectionPool(host='127.0.0.1', port=58956): Read timed out. (read timeout=<object object at 0x103af7140>)

我可以改变互联网功能作为一种解决办法,但我不明白为什么插座会干扰硒:

^{pr2}$

Tags: httphostclosereturnporthtmldrivertimeout
1条回答
网友
1楼 · 发布于 2024-06-10 19:32:38

documentation

socket.setdefaulttimeout(timeout)

Set the default timeout in seconds (float) for new socket objects. When the socket module is first imported, the default is None. See settimeout() for possible values and their respective meanings.

问题是setdefaulttimeout为所有新创建的套接字设置超时,因此也为Selenium设置超时。它是一个全局套接字库设置。在

如果只想对此套接字实例使用超时,请使用socket.settimeout(value)doc)。在

^{1}$

相关问题 更多 >