让 selenium 在 pythonanywhere 上工作

Getting selenium to work on pythonanywhere

我的理解是 pythonanywhere 支持无头 Firefox 浏览器,但你需要

from pyvirtualdisplay import Display

因此您可以使用

进行连接
with Display():
    while True:
        try:
            driver = webdriver.Firefox()
            break
        except:
            time.sleep(3)

而且我连接正常。但是,在我开始使用带有

的驱动程序之后
with Display():
    while True:
        try:
            driver = webdriver.Firefox()
            break
        except:
            time.sleep(3)
    wb=load_workbook(r'/home/hoozits728/mutual_fund_tracker/Mutual_Fund_Tracker.xlsx')
    ws=wb.get_sheet_by_name('Tactical')

    for i in range(3, ws.max_row+1):
        if ws.cell(row=i,column=2).value is not None:
            driver.get('https://finance.yahoo.com/quote/' + ws.cell(row=i,column=2).value + '/performance?ltr=1')
            oneyear=driver.find_element_by_css_selector('#Col1-0-Performance-Proxy > section > div:nth-child(2) > div > div:nth-child(5) > span:nth-child(2)').text
            threeyear=driver.find_element_by_css_selector('#Col1-0-Performance-Proxy > section > div:nth-of-type(2) > div > div:nth-of-type(6) > span:nth-of-type(2)').text
            fiveyear=driver.find_element_by_css_selector('#Col1-0-Performance-Proxy > section > div:nth-of-type(2) > div > div:nth-of-type(7) > span:nth-of-type(2)').text
            ws.cell(row=i,column=10).value=oneyear
            ws.cell(row=i,column=11).value=threeyear
            ws.cell(row=i,column=12).value=fiveyear

           … and so on …

过了一会儿我收到这个错误

就其价值而言,这段代码在我的本地机器上运行得非常好。另外我是付费会员,应该不会有白名单问题。

您收到该错误是因为 selenium 无法连接到您创建的浏览器。如果您 运行 正在执行第一段代码,然后是第二段代码,那么显示已经关闭,这可能会导致浏览器崩溃。

您需要运行使用浏览器的代码 with 块中。

PythonAnywhere 帮助页面上有一个示例,展示了如何以最可靠的方式执行所有这些操作。

我最近了解到,yahoo 已阻止 pythonanywhere 运行 任何网络抓取脚本。我假设这对所有 AWS 服务器和使用它们的人都是如此,但我不是 100% 确定这一点。我希望这对遇到这个问题的人有所帮助。

https://www.pythonanywhere.com/forums/topic/5724/#id_post_52307