Python实现爬取需要登录的网站完整示例
from selenium import webdriver
dirver = webdriver.Firefox()
dirver.get('https://music.douban.com/')
for i in dirver.find_elements_by_css_selector('.new-albums .album-title'):
print(i.text)
读取页面整合后的结果
import requests
from lxml import html
# 创建 session 对象。这个对象会保存所有的登录会话请求。
session_requests = requests.session()
# 提取在登录时所使用的 csrf 标记
login_url = "https://bitbucket.org/account/signin/?next=/"
result = session_requests.get(login_url)
tree = html.fromstring(result.text)
authenticity_token = list(set(tree.xpath("//input[@name='csrfmiddlewaretoken']/@value")))[0]
payload = {
"username": "<你的用户名>",
"password": "<你的密码>",
"csrfmiddlewaretoken": authenticity_token # 在源代码中,有一个名为 “csrfmiddlewaretoken” 的隐藏输入标签。
}
# 执行登录
result = session_requests.post(
login_url,
data = payload,
headers = dict(referer=login_url)
)
# 已经登录成功了,然后从 bitbucket dashboard 页面上爬取内容。
url = 'https://bitbucket.org/dashboard/overview'
result = session_requests.get(
url,
headers = dict(referer = url)
)
# 测试爬取的内容
tree = html.fromstring(result.content)
bucket_elems = tree.findall(".//span[@class='repo-name']/")
bucket_names = [bucket.text_content.replace("n", "").strip() for bucket in bucket_elems]
print(bucket_names)
from bs4 import BeautifulSoup
import requests class CSDN(object):
def __init__(self, headers):
self.session = requests.Session()
self.headers = headers
def get_webflow(self):
url = 'http://passport.csdn.net/account/login'
response = self.session.get(url=url, headers=self.headers)
soup = BeautifulSoup(response.text, 'html.parser')
lt = soup.find('input', {'name': 'lt'})['value']
execution = soup.find('input', {'name': 'execution'})['value']
soup.clear()
return (lt, execution)
def login(self, account, password):
self.username = account
self.password = password
lt, execution = self.get_webflow()
data = {
'username': account,
'password': password,
'lt': lt,
'execution': execution,
'_eventId': 'submit'
}
url = 'http://passport.csdn.net/account/login'
response = self.session.post(url=url, headers=self.headers, data=data)
if (response.status_code == 200):
print('正常')
else:
print('异常')
def func(self):
headers1={
'Host':'write.blog.csdn.net',
'Upgrade-Insecure-Requests':'',
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'
}
response=self.session.get(url='http://write.blog.csdn.net/postlist',headers=headers1,allow_redirects=False)
print(response.text)
if __name__ == '__main__':
headers = {
'Host': 'passport.csdn.net',
'Origin': 'http://passport.csdn.net',
'Referer':'http://passport.csdn.net/account/login',
'Upgrade-Insecure-Requests':'',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36',
}
csdn = CSDN(headers=headers)
account = ''
password = ''
csdn.login(account=account, password=password)
csdn.func()
#coding=utf-
import requests
import re
import time
import json
from bs4 import BeautifulSoup as BS
import sys headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36',
} def Get_Movie_URL():
urls = []
for i in range(,):
# 第一页的URL是不一样的,需要另外进行处理
if i != :
url = "http://www.mtime.com/top/movie/top100/index-%d.html" % i
else:
url = "http://www.mtime.com/top/movie/top100/"
r = requests.get(url=url,headers=headers)
soup = BS(r.text,'lxml')
movies = soup.find_all(name='a',attrs={'target':'_blank','href':re.compile('http://movie.mtime.com/(\d+)/'),'class':not None})
for m in movies:
urls.append(m.get('href'))
return urls def Create_Ajax_URL(url):
movie_id = url.split('/')[-]
t = time.strftime("%Y%m%d%H%M%S0368", time.localtime())
ajax_url = "http://service.library.mtime.com/Movie.api?Ajax_CallBack=true&Ajax_CallBackType=Mtime.Library.Services&Ajax_CallBackMethod=GetMovieOverviewRating&Ajax_CrossDomain=1&Ajax_RequestUrl=%s&t=%s&Ajax_CallBackArgument0=%s" % (url,t,movie_id)
return ajax_url def Crawl(ajax_url):
r = requests.get(url=ajax_url,headers=headers)
if r.status_code == :
r.encoding = 'utf-8'
result = re.findall(r'=(.*?);',r.text)[]
if result is not None:
value = json.loads(result) movieTitle = value.get('value').get('movieTitle')
TopListName = value.get('value').get('topList').get('TopListName')
Ranking = value.get('value').get('topList').get('Ranking')
movieRating = value.get('value').get('movieRating')
RatingFinal = movieRating.get('RatingFinal')
RDirectorFinal = movieRating.get('RDirectorFinal')
ROtherFinal = movieRating.get('ROtherFinal')
RPictureFinal = movieRating.get('RPictureFinal')
RStoryFinal = movieRating.get('RStoryFinal')
print(movieTitle)
if value.get('value').get('boxOffice'):
TotalBoxOffice = value.get('value').get('boxOffice').get('TotalBoxOffice')
TotalBoxOfficeUnit = value.get('value').get('boxOffice').get('TotalBoxOfficeUnit')
print('票房:%s%s' % (TotalBoxOffice,TotalBoxOfficeUnit))
print('%s——No.%s' % (TopListName,Ranking))
print('综合评分:%s 导演评分:%s 画面评分:%s 故事评分:%s 音乐评分:%s' %(RatingFinal,RDirectorFinal,RPictureFinal,RStoryFinal,ROtherFinal))
print('****' * ) def main():
urls = Get_Movie_URL()
for u in urls:
Crawl(Create_Ajax_URL(u)) # 问题所在,请求如下单个电影链接时时不时会爬取不到数据
# Crawl(Create_Ajax_URL('http://movie.mtime.com/98604/')) if __name__ == '__main__':
main()
相关工具
链接: https://pan.baidu.com/s/1oEw_MsaAWcMx7NQII6jXYg 密码: e6b6
链接: https://pan.baidu.com/s/1fSppM-hK2x9Jk9RGqvRMqg 密码: 4q43
Python实现爬取需要登录的网站完整示例的更多相关文章
- 如何用 Python 爬取需要登录的网站
[原文地址:]http://python.jobbole.com/83588/ import requests from lxml import html # 创建 session 对象.这个对象会保 ...
- Python简单爬取Amazon图片-其他网站相应修改链接和正则
简单爬取Amazon图片信息 这是一个简单的模板,如果需要爬取其他网站图片信息,更改URL和正则表达式即可 1 import requests 2 import re 3 import os 4 de ...
- requests库爬取需要登录的网站
#!usr/bin/env python #-*- coding:utf-8 _*- """ @author:lenovo @file: 登录人人网.py @time: ...
- Jsoup爬取带登录验证码的网站
今天学完爬虫之后想的爬一下我们学校的教务系统,可是发现登录的时候有验证码.因此研究了Jsoup爬取带验证码的网站: 大体的思路是:(需要注意的是__VIEWSTATE一直变化,所以我们每个页面都需要重 ...
- Python:爬取网站图片并保存至本地
Python:爬取网页图片并保存至本地 python3爬取网页中的图片到本地的过程如下: 1.爬取网页 2.获取图片地址 3.爬取图片内容并保存到本地 实例:爬取百度贴吧首页图片. 代码如下: imp ...
- 用Python爬虫爬取广州大学教务系统的成绩(内网访问)
用Python爬虫爬取广州大学教务系统的成绩(内网访问) 在进行爬取前,首先要了解: 1.什么是CSS选择器? 每一条css样式定义由两部分组成,形式如下: [code] 选择器{样式} [/code ...
- Python+Selenium爬取动态加载页面(1)
注: 最近有一小任务,需要收集水质和水雨信息,找了两个网站:国家地表水水质自动监测实时数据发布系统和全国水雨情网.由于这两个网站的数据都是动态加载出来的,所以我用了Selenium来完成我的数据获取. ...
- 使用Python爬虫爬取网络美女图片
代码地址如下:http://www.demodashi.com/demo/13500.html 准备工作 安装python3.6 略 安装requests库(用于请求静态页面) pip install ...
- Python爬虫|爬取喜马拉雅音频
"GOOD Python爬虫|爬取喜马拉雅音频 喜马拉雅是知名的专业的音频分享平台,用户规模突破4.8亿,汇集了有声小说,有声读物,儿童睡前故事,相声小品等数亿条音频,成为国内发展最快.规模 ...
随机推荐
- 关于vertical-align和line-height的真知灼见
本文的重点是了解vertical-align和line-height的使用 涉及到的名词:基线,底端,行内框,行框,行间距,替换元素及非替换元素,对齐.只有充分理解这些概念才会灵活运用这两个属性. 什 ...
- POJ-1511 Invitation Cards---Dijkstra+队列优化+前向星正向反向存图
题目链接: https://vjudge.net/problem/POJ-1511 题目大意: 给定节点数n,和边数m,边是单向边. 问从1节点出发到2,3,...n 这些节点路程和从从这些节点回来到 ...
- [转]scrapy中的request.meta
作者:知乎用户链接:https://www.zhihu.com/question/54773510/answer/146971644 meta属性是字典,字典格式即{'key':'value'},字典 ...
- 使用hue查看hdfs系统报无法访问:/user/hadoop。 Note: you are a Hue admin but not a HDFS superuser, "hdfs" or part of HDFS supergroup, "supergroup".
出现这个问题,是因为默认的超级用户是hdfs ,我的是hadoop用户登录的, 也就是说首次登录hadoop这个用户是我的超级用户 此时只需要将hue.ini配置改为 然后重启即可.
- 阿里云、腾讯云开通端口 telnet不通的原因
1.安全组是否已经开通相对应的端口: 阿里云:https://help.aliyun.com/document_detail/25471.html 腾讯云:http://bbs.qcloud.com/ ...
- [LeetCode] Design Log Storage System 设计日志存储系统
You are given several logs that each log contains a unique id and timestamp. Timestamp is a string t ...
- hosts管理工具1.0发布了。。。。
hosts管理工具1.0发布了.... 可以快速管理hosts文件了,再也不用打开系统盘,一个目录一个目录的查找了. 快速方便的修改host文件,一键保存. 可快速注释当前行,或者取消注释当前行,只需 ...
- ReactNative Android之原生UI组件动态addView不显示问题解决
ReactNative Android之原生UI组件动态addView不显示问题解决 版权声明:本文为博主原创文章,未经博主允许不得转载. 转载请表明出处:http://www.cnblogs.com ...
- [AtCoder arc090F]Number of Digits
Description 题库链接 记 \(d\) 在十进制下的位数为 \(f(d)\) .给出询问 \(S\) ,求有多少对 \((l,r)\) 使得 \[\sum_{i=l}^r f(i)=S\] ...
- [NOI2009]变换序列
Description Input Output Sample Input 5 1 1 2 2 1 Sample Output 1 2 4 0 3 HINT 30%的数据中N≤50: 60%的数据中N ...