首页 > 解决方案 > 如何在抓取网站过程中自动登录?

问题描述

我正在尝试使用代码 ( for i in range(0,16)) 从具有多个页面(从第 1 页到第 17 页)的网站中抓取数据。下面是我正在使用的代码,它可以工作。

import requests
import lxml.html as lh
import pandas as pd
import numpy as np

for i in range(0,16):
    URL = 'https://pvoutput.org/list.jsp?p={}&id=82699&sid=73313&gs=0&v=0&o=date&d=desc'.format(i)
    page = requests.get(URL)
    doc = lh.fromstring(page.content)
    tr_elements = doc.xpath('//tr')

    col=[]
    i=0

    for t in tr_elements[3]:
        i+=1
        name=t.text_content()
        print('%d:"%s"'%(i, name))
        col.append((name, []))

例如,在每一页中,有一个表,我想从表的第 4 行刮取数据(这里的数据是表的表头,只是现在)(for t in tr_elements[3])并将每一页的所有数据保存在数组中col

作为结果:

...
1:"Date▼"
2:"Generated"
3:"Efficiency"
4:"Exported"
5:"Peak Power"
6:"Peak Time"
7:"Conditions"
8:"Temperature"
9:"Comments"
1:"Date▼"
2:"Generated"
3:"Efficiency"
4:"Exported"
5:"Peak Power"
6:"Peak Time"
7:"Conditions"
8:"Temperature"
9:"Comments"
1:"Don't have a login? Register in 10 seconds.  Forgot Password?"
1:"Don't have a login? Register in 10 seconds.  Forgot Password?"
1:"Don't have a login? Register in 10 seconds.  Forgot Password?"
...

现在的问题是,当程序继续在下一页中抓取数据时,它会在继续之前开始要求登录。

有什么方法或方法可以解决这个问题吗?

标签: pythonweb-scraping

解决方案


看起来您需要登录才能从最后 3 页获取结果。该站点使用 javascript 对象,因为所有这些站点都需要登录。你现在需要学习 selenium,因为当我试图抓取这样的网站时,同样的事情发生在我身上。Selenium 是您实现此目的的工具。


推荐阅读