让硒在Python身上发挥作用

2024-04-19 17:54:40 发布

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

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

from pyvirtualdisplay import Display

所以你可以用

^{pr2}$

我连接得很好。但是,在我开始使用

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 …

过了一会儿我就犯了这个错误

enter image description here

不管怎样,这段代码在我的本地机器上运行得非常好。另外,我是付费会员,所以不应该有白名单问题。在


Tags: ofdivbywsvaluetypedrivercell
2条回答

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

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

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

据我最近了解,雅虎已经阻止pythonanywhere运行任何网页抓取脚本。我不确定这些服务器中有100%是真的。我希望这能帮助任何遇到这个问题的人。在

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

相关问题 更多 >