python如何示例爬虫代码


本文摘自php中文网,作者coldplay.xixi,侵删。

python爬虫代码示例的方法:首先获取浏览器信息,并使用urlencode生成post数据;然后安装pymysql,并存储数据到MySQL即可。

python爬虫代码示例的方法:

1、urllib和BeautifuSoup

获取浏览器信息

1

2

3

from urllib import request

req = request.urlopen("http://www.baidu.com")

print(req.read().decode("utf-8"))

模拟真实浏览器:携带user-Agent头

(目的是不让服务器认为是爬虫,若不带此浏览器信息,则可能会报错)

1

2

3

4

req = request.Request(url) #此处url为某个网址

req.add_header(key,value)  #key即user-Agent,value即浏览器的版本信息

resp = request.urlopen(req)

print(resp.read().decode("utf-8"))

相关学习推荐:python视频教程

使用POST

导入urllib库下面的parse

1

from urllib import parse

使用urlencode生成post数据

1

2

3

4

5

postData = parse.urlencode([

    (key1,val1),

    (key2,val2),

    (keyn,valn)

])

使用post

1

2

3

request.urlopen(req,data=postData.encode("utf-8")) #使用postData发送post请求

resp.status  #得到请求状态

resp.reason #得到服务器的类型

完整代码示例(以爬取维基百科首页链接为例)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

#-*- coding:utf-8 -*-

from bs4 import BeautifulSoup as bs

from urllib.request import urlopen

import re

import ssl

#获取维基百科词条信息

ssl._create_default_https_context = ssl._create_unverified_context #全局取消证书验证

#请求URL,并把结果用utf-8编码

req = urlopen("https://en.wikipedia.org/wiki/Main page").read().decode("utf-8")

#使用beautifulsoup去解析

soup = bs(req,"html.parser")

# print(soup)

#获取所有href属性以“/wiki/Special”开头的a标签

urllist = soup.findAll("a",href=re.compile("^/wiki/Special"))

for url in urllist:

#去除以.jpg或.JPG结尾的链接

if not re.search("\.(jpg|JPG)$",url["href"]):

#get_test()输出标签下的所有内容,包括子标签的内容;

#string只输出一个内容,若该标签有子标签则输出“none

print(url.get_text()+"----->"+url["href"])

# print(url)

2、存储数据到MySQL

安装pymysql

通过pip安装:

1

$ pip install pymysql

或者通过安装文件:

1

$ python setup.py install

使用

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

#引入开发包

import pymysql.cursors

#获取数据库链接

connection = pymysql.connect(host="localhost",

user = 'root',

password = '123456',

db ='wikiurl',

charset = 'utf8mb4')

try:

#获取会话指针

with connection.cursor() as cursor

#创建sql语句

sql = "insert into `tableName`(`urlname`,`urlhref`) values(%s,%s)"

#执行SQL语句

cursor.execute(sql,(url.get_text(),"https://en.wikipedia.org"+url["href"]))

#提交

connection.commit()

finally:

#关闭

connection.close()

3、爬虫注意事项

Robots协议(机器人协议,也称爬虫协议)全称是“网络爬虫排除协议”,网站通过Robots协议告诉搜索引擎哪些页面可以抓取,哪些页面不可以抓取。一般在主页面下,如https://en.wikipedia.org/robots.txt

1

2

Disallow:不允许访问

allow:允许访问

相关推荐:编程视频课程

以上就是python如何示例爬虫代码的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

Python什么时候出现的

Python利用os模块批量修改文件名的方法介绍(附代码)

Python枚举类定义及作用(实例解析)

老男孩Python高级运维实战精品进阶视频教程的资源分享

Python中的for循环语句怎么写

Python输出hello world代码的方法

Python爬虫如何设置代理ip

Python如何识别图片中的文字

32位的电脑怎么下载Python

Python正则表达式和re库的相关内容介绍(代码示例)

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...