当前位置: 首页 > 面试题库 >

如何抓取需要首先使用Python登录的网站

尤俊誉
2023-03-14
问题内容

首先,我认为值得一提,我知道有很多类似的问题,但是没有一个对我有用。

我是Python,html和网络抓取工具的新手。我正在尝试从需要先登录的网站上抓取用户信息。在我的测试中,我以来自github的scraper我的电子邮件设置为例。主页是“
https://github.com/login ”,目标页面是“
https://github.com/settings/emails ”

这是我尝试过的方法列表

##################################### Method 1
import mechanize
import cookielib
from BeautifulSoup import BeautifulSoup
import html2text

br = mechanize.Browser()
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)

# Browser options
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)


br.addheaders = [('User-agent', 'Chrome')]

# The site we will navigate into, handling it's session
br.open('https://github.com/login')

for f in br.forms():
    print f

br.select_form(nr=0)

# User credentials
br.form['login'] = 'myusername'
br.form['password'] = 'mypwd'

# Login
br.submit()

br.open('github.com/settings/emails').read()


################ Method 2
import urllib, urllib2, cookielib

username = 'myusername'
password = 'mypwd'

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('https://github.com/login', login_data)
resp = opener.open('https://github.com/settings/emails')
print resp.read()



############# Method 3
import urllib
opener = urllib.FancyURLopener()
print opener.open('http://myusername:mypwd@github.com/settings/emails').read()




########## Method 4
import mechanize
import cookielib

br = mechanize.Browser()
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)

br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
#br.set_debug_http(True)
#br.set_debug_redirects(True)
#br.set_debug_responses(True)

br.addheaders = [('User-agent', 'Chrome')]

br.add_password('https://github.com/settings/emails', 'myusername', 'mypwd')
br.open('https://github.com/settings/emails')
print br.response().read()



############ Methods 5
from requests import session

payload = {
    'action': 'login',
    'username': 'myusername',
    'password': 'mypwd'
}

with session() as c:
    c.post('https://github.com/login', data=payload)
    request = c.get('https://github.com/settings/emails')
    print request.headers
    print request.text



########### Method 6
import requests
from requests.packages.urllib3 import add_stderr_logger
import sys
from bs4 import BeautifulSoup as bs

add_stderr_logger()
s = requests.Session()

s.headers['User-Agent'] = 'Chrome'

username = 'myusername'
password = 'mypwd'
url = 'https://github.com/login'

# after examining the HTML of the website you're trying to log into
# set name_form to the name of the form element that contains the name and
# set password_form to the name of the form element that will contain the password
login = {'login': username, 'password': password}
login_response = s.post(url, data=login)
for r in login_response.history:
    if r.status_code == 401:  # 401 means authentication failed
        print 'error!'
        sys.exit(1)  # abort


pdf_response = s.get('https://github.com/settings/emails')  # Your cookies and headers are automatically included
soup = bs(pdf_response.content)

我也阅读了一些有关HTTP身份验证和cookie之间差异的讨论。仍然没有一个工作。

请帮助,任何帮助将不胜感激。非常感谢你。


问题答案:

这对我有用:

##################################### Method 1
import mechanize
import cookielib
from BeautifulSoup import BeautifulSoup
import html2text

# Browser
br = mechanize.Browser()

# Cookie Jar
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)

# Browser options
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)

br.addheaders = [('User-agent', 'Chrome')]

# The site we will navigate into, handling it's session
br.open('https://github.com/login')

# View available forms
for f in br.forms():
    print f

# Select the second (index one) form (the first form is a search query box)
br.select_form(nr=1)

# User credentials
br.form['login'] = 'mylogin'
br.form['password'] = 'mypass'

# Login
br.submit()

print(br.open('https://github.com/settings/emails').read())

你一点也不远!



 类似资料:
  • 问题内容: 如果我想抓取一个需要先使用密码登录的网站,我该如何使用beautifulsoup4库开始使用python抓取它?以下是我对不需要登录的网站的处理方式。 应该如何更改代码以适应登录?假设我要抓取的网站是一个需要登录的论坛。一个示例是http://forum.arduino.cc/index.php 问题答案: 您可以使用机械化: 或urllib-使用urllib2登录网站

  • 本文向大家介绍对python抓取需要登录网站数据的方法详解,包括了对python抓取需要登录网站数据的方法详解的使用技巧和注意事项,需要的朋友参考一下 scrapy.FormRequest login.py selenium登录获取cookie get_cookie_by_selenium.py 获取浏览器cookie(以Ubuntu的Firefox为例) get_cookie_by_firefo

  • 问题内容: 我的问题是,它不仅需要基本的cookie,而且还要求会话cookie和随机生成的ID。我认为这意味着我需要将Web浏览器模拟器与Cookie罐一起使用? 我曾尝试使用Snoopy,Goutte和其他一些Web浏览器模拟器,但到目前为止,我还无法找到有关如何接收Cookie的教程。我有点绝望了! 谁能给我一个如何在史努比或古特接受饼干的例子吗? 提前致谢! 问题答案: 然后,我们应该能够

  • 问题内容: 我遇到过许多教程,它们解释了如何使用node.js刮取不需要身份验证/登录的公共网站。 有人可以解释如何抓取需要使用node.js登录的网站吗? 问题答案: 使用Mikeal的请求库,您需要启用cookie支持,如下所示: 因此,您首先应该在该站点上(手动)创建一个用户名,并在向该站点发出POST请求时将用户名和密码作为参数传递。之后,服务器将使用Cookie进行响应,该请求将记住该C

  • ''我想为需要登录的网站执行网页抓取。我尝试了两种不同的代码方法。我仍然无法执行登录。“”#使用BeautifulSoup在Python中开发代码: #第一种方法是从bs4导入请求导入http。cookiejar导入urllib。请求导入urllib。作语法分析 'http://127.0.0.1/orangehrm4.3.1/symfony/web/index.php/auth/login' #

  • 问题内容: 我看到了另一个问题:如何使用Python登录网页并检索cookie以供以后使用? 但是,对该答案进行直接修改对我不起作用,因此我想知道如何实现我的目标。 为了提供上下文,我尝试登录,然后从以下页面中提取播放列表的名称: 我认为对于知道自己在做什么的人来说,这应该很简单。一些基本的代码可以登录到该网站并访问受密码保护的页面,这非常棒,如果您能用一两句话来解释代码中的每一行在做什么,那会更