python -使用Requests库完成Post表单操作
"""
使用Requests库完成Post表单操作
"""
#_*_codingn:utf8 _*_
import requests from bs4 import BeautifulSoup '''
设置请求头,让程序发出的请求更像来源于浏览器
'''
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36(KHTML, like Gecko) Chrome/43.0.2357.124 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"} if __name__ == "__main__": params ={"username": "anything","password": "password"} session =requests.session()
post_obj = session.post("http://pythonscraping.com/pages/cookies/welcome.php", params) s = session.get("http://pythonscraping.com/pages/cookies/profile.php")
print(post_obj.text.encode("utf-8"))
print(s.text.encode("utf-8")) #session.cookies.get_dict() #获取cooking
print(session.cookies.get_dict())
# -*- coding: utf-8 -*-
'''
目标站点分析
网页结构分析
--开干--
1、单页内容
2、正则
3、保存json
4、多线程循环
'''
# .*具有贪婪的性质,首先匹配到不能匹配为止,根据后面的正则表达式,会进行回溯。
# .*?(短)则相反,一个匹配以后,就往下进行,所以不会进行回溯,具有最小匹配的性质。
# re.S 让.匹配换行符
#----------------------------------
import json
import requests
from requests.exceptions import RequestException
import re
import time
from multiprocessing import Pool headers = { # 非常重要
'Accept-Language': 'en-US,en;q=0.8',
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36',
'Connection': 'keep-alive',
'Referer': 'http://maoyan.com/board/6'
} def get_one_page(url):
try:
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.text
return None # 非200
except RequestException:
return None def parse_one_page(html):
pattern = re.compile('<dd>.*?board-index.*?>(\d+)</i>.*?data-src="(.*?)".*?name"><a'
+ '.*?>(.*?)</a>.*?star">(.*?)</p>.*?releasetime">(.*?)</p>'
+ '.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>', re.S)
items = re.findall(pattern, html)
for item in items:
yield { # 变成生成器
'index': item[0],
'image': item[1],
'title': item[2],
'actor': item[3].strip()[3:], # 字符串处理 (移除字符串头尾指定的字符序列)
'time': item[4].strip()[5:],
'score': item[5] + item[6] # 分开匹配加起来
} def write_to_file(content):
with open('result.txt', 'a', encoding='utf-8') as f: # 编码3
f.write(json.dumps(content, ensure_ascii=False) + '\n') # json.dumps 序列化时对中文默认使用的ascii编码 def main(offset):
url = 'http://maoyan.com/board/4?offset=' + str(offset)
html = get_one_page(url) # return返回参数
# print(html)
for item in parse_one_page(html):
# print(item)
write_to_file(item) if __name__ == '__main__':
for i in range(10):
main(offset=i * 10)
time.sleep(1)
# 进程池
# pool=Pool() # pool.map(main,[i*10 for i in range(10)])
# coding=utf-8 '''
1、抓取索引页内容
2、抓取详情页内容
3、下载图片保存数据库
4、循环及多线程
''' import requests
from requests.exceptions import RequestException
from json import loads
from bs4 import BeautifulSoup
user_agent = "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)"
headers = {"User-Agent": user_agent} def get_onepage_index(i, keywords):
data = {
"offset": i,
"format": "json",
"keyword": keywords,
"autoload": "true",
"count": "",
"cur_tab": "",
"from": "search_tab"
}
url = 'https://www.toutiao.com/search_content/?'
try:
response = requests.get(url, params=data)
if response.status_code == 200:
return response.text
return None
except RequestException:
print('something is wrong!')
return None def parse_onepage_index(html):
# json.loads()用于将str类型的数据转成dict。
data = loads(html)
if data and 'data' in data.keys(): ##获取所有的key 值
for item in data.get('data'): # get() 函数返回指定键的值,如果值不在字典中返回默认值。
yield item.get('article_url') def get_page_detail(url):
try:
response = requests.get(url, headers=headers)
if response.status_code == 200:
# print(response.status_code)
return response.text
return None
except RequestException:
print('wrong url:', url)
return None def parsepage(html):
soup = BeautifulSoup(html, 'lxml')
title = soup.title.string
print(title) def main():
for i in range(1, 2):
i = str(i * 20)
html = get_onepage_index(i, '街拍')
parse_onepage_index(html)
for url in parse_onepage_index(html):
print(url)
detailhtml = get_page_detail(url) # 返回网页文本
# print(detailhtml)
if detailhtml == None:
pass
else:
parsepage(detailhtml) # bs4去解析 # get_page_detail('http://toutiao.com/group/6596305324645286404/') if __name__ == '__main__':
main()
如有疑问,请留言。
如觉得有帮助,请点个赞,谢谢!
python -使用Requests库完成Post表单操作的更多相关文章
- 【转】使用Python的Requests库进行web接口测试
原文地址:使用Python的Requests库进行web接口测试 1.Requests简介 Requests 是使用 Apache2 Licensed 许可证的 HTTP 库.用 Python 编写, ...
- Python爬虫—requests库get和post方法使用
目录 Python爬虫-requests库get和post方法使用 1. 安装requests库 2.requests.get()方法使用 3.requests.post()方法使用-构造formda ...
- 解决python的requests库在使用过代理后出现拒绝连接的问题
在使用过代理后,调用python的requests库出现拒绝连接的异常 问题 在windows10环境下,在使用代理(VPN)后.如果在python中调用requests库来地址访问时,有时会出现这样 ...
- Python的Django框架中forms表单类的使用方法详解
用户表单是Web端的一项基本功能,大而全的Django框架中自然带有现成的基础form对象,本文就Python的Django框架中forms表单类的使用方法详解. Form表单的功能 自动生成HTML ...
- 【python 】Requests 库学习笔记
概览 实例引入 import requests response = requests.get('https://www.baidu.com/') print(type(response)) prin ...
- 第一百五十九节,封装库--JavaScript,表单序列化结合ajax提交数据
封装库--JavaScript,表单序列化结合ajax提交数据 封装库,表单序列化方法 /** xu_lie_biao_dan()方法,表单序列化方法,将自动获取指定表单里面的各项字段name值和va ...
- 第一百五十四节,封装库--JavaScript,表单验证--提交验证
封装库--JavaScript,表单验证--提交验证 将表单的所有必填项,做一个判断函数,填写正确时返回布尔值 最后在提交时,判断每一项是否正确,全部正确才可以 提交 html <div id= ...
- 第一百五十三节,封装库--JavaScript,表单验证--备注字数验证
封装库--JavaScript,表单验证--备注字数验证 效果图 html <div id="reg"> <h2 class="tuo"> ...
- 第一百五十二节,封装库--JavaScript,表单验证--年月日注入
封装库--JavaScript,表单验证--年月日注入 效果图 html <div id="reg"> <h2 class="tuo"> ...
随机推荐
- python实现线性回归之简单回归
代码来源:https://github.com/eriklindernoren/ML-From-Scratch 首先定义一个基本的回归类,作为各种回归方法的基类: class Regression(o ...
- Windows挂载Gluster复制卷
本地挂载测试 mount -t glusterfs 127.0.0.1:/gv1 /mnt [root@gluster1 mnt]# df -h Filesystem Size Used Avail ...
- latex-列表环境
介绍 latex 主要有三种列表环境,进行罗列的实现, 无序列表 -- itemize 有序列表 -- enumerate 描述列表 -- description 本文进行了一一介绍和演示, 同时添加 ...
- Uva 1754 Posterize
#include<bits/stdc++.h> using namespace std; #define rep(i,a,b) for(int i=a;i<=b;++i) #defi ...
- FZU 1894 志愿者选拔
Problem 1894 志愿者选拔 Accept: 2308 Submit: 7003 Time Limit: 1500 mSec Memory Limit : 32768 KB Problem D ...
- Floyd —Warshall(最短路及其他用法详解)
一.多元最短路求法 多元都求出来了,单源的肯定也能求. 思想是动态规划的思想:从任意节点A到任意节点B的最短路径不外乎2种可能,1是直接从A到B,2是从A经过若干个节点X到B.所以,我们假设Dis(A ...
- ACM一年记,总结报告(希望自己可以走得很远)
一. 知识点梳理 (一) 先从工具STL说起: 容器学习了:stack,queue,priority_queue,set/multiset,map/multimap,vector. 1.stack: ...
- Git上传本地仓库项目到gitee远程仓库(命令篇)
前言:最近整理了一下自己之前的自学代码,包括一些练习的项目.发现有些杂乱,故想使用Gitte(码云)管理.加上不少公司使用Git,所以写了这篇文章记录. 如果我们本地有了项目,那么如何上传到码云上呢? ...
- thinkphp日志泄露扫描
import requests,sys dirpath=[] def dirscan(url,year): for i in range(1,13): if i < 10: urls=url+' ...
- HashMap 底层探索
其实HashMap就是一个Node数组,只是这个数组很奇怪它的每一个Node节点都有自己的下一个Node;这个是hashMap的Node的源码: static class Node<K,V> ...