从0开始学爬虫8使用requests/pymysql和beautifulsoup4爬取维基百科词条链接并存入数据库
从0开始学爬虫8使用requests和beautifulsoup4爬取维基百科词条链接并存入数据库
Python使用requests和beautifulsoup4爬取维基百科词条链接并存入数据库
参考文档:
https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/
# 安装 beautifulsoup4
(pytools) D:\python\pytools>pip install beautifulsoup4
安装mysql的模块
pymysql的地址:https://github.com/PyMySQL/PyMySQL
爬取维基百科词条
# coding=utf-8 from bs4 import BeautifulSoup
import requests
import re def spider_wike():
url = "https://en.wikipedia.org/wiki/Main_Page"
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"}
resp = requests.get(url, headers = headers)
# 将响应数据转换为utf-8编码
resp.encoding = 'utf-8' html_doc = resp.text soup = BeautifulSoup(html_doc, "html.parser")
# 找到以wiki开头的a标签的href属性
list_urls = soup.find_all("a", href=re.compile("^/wiki/"))
# print(list_urls) # 输出所有的词条对应的名称和URL
for url in list_urls:
# 过滤掉.jpg 或.JPG 结尾的URL
if not re.search(r"\.(jpg|JPG)", url["href"]):
# 词条加网址
# sting只能获取一个, get_text() 可以获取标签下所有的内容
print(url.get_text(), " <------>", "https://en.wikipedia.org" + url["href"]) if __name__ == '__main__':
spider_wike()
# 将维基百科词条链接存入数据库
# coding=utf-8 from bs4 import BeautifulSoup
import requests
import re
import pymysql.cursors '''
# 环境准备
pip install pymysql
create database wikiurl charset=utf8mb4;
use wikiurl;
create table urls (id int primary key auto_increment,urlname varchar(255),urlhref varchar(1000));
'''
url = "https://en.wikipedia.org/wiki/Main_Page"
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"}
resp = requests.get(url, headers = headers)
# 将响应数据转换为utf-8编码
resp.encoding = 'utf-8' html_doc = resp.text soup = BeautifulSoup(html_doc, "html.parser")
# 找到以wiki开头的a标签的href属性
list_urls = soup.find_all("a", href=re.compile("^/wiki/"))
# print(list_urls) # 输出所有的词条对应的名称和URL
for url in list_urls:
# 过滤掉.jpg 或.JPG 结尾的URL
if not re.search(r"\.(jpg|JPG)", url["href"]):
# 词条加网址
# sting只能获取一个, get_text() 可以获取标签下所有的内容
print(url.get_text(), " <------>", "https://en.wikipedia.org" + url["href"]) connection = pymysql.connect(host='localhost',
user='root',
password='root',
db='wikiurl',
charset='utf8mb4')
try:
# 获取回话指针
with connection.cursor() as cursor:
# 创建sql语句
sql = "insert into `urls`(`urlname`,`urlhref`) values(%s,%s)" # 执行sql语句
cursor.execute(sql,(url.get_text(), "https://en.wikipedia.org" + url["href"]))
# 提交数据
connection.commit()
finally:
connection.close()
# 从数据库读取词条信息
# coding=utf-8 import pymysql def get_conn():
connection = pymysql.connect(host='localhost',
user='root',
password='root',
db='wikiurl',
charset='utf8mb4')
return connection def get_wiki_data():
conn = get_conn() sql = "select `urlname`,`urlhref` from urls"
cur = conn.cursor()
# 获取总记录条数
count = cur.execute(sql)
print(count) # 获取所有数据
# urllists = cur.fetchall()
# 获取指定条目数据
# urllists = cur.fetchmany(3)
#
# for url in urllists:
# print(url[0],'<--->',url[1]) # 获取一条数据
link = cur.fetchone()
print(link) # 关闭数据库连接
conn.close() def get_data():
conn = get_conn() try:
with conn.cursor() as cur:
sql = "select `urlname`,`urlhref` from urls where `id` is not NULL"
count = cur.execute(sql)
print(count) # 查询所有数据
# data = cur.fetchall()
# print(data) # 查询指定条目数据
result = cur.fetchmany(size = 5)
print(result)
finally:
conn.close() if __name__ == '__main__':
# get_wiki_data()
get_data()
从0开始学爬虫8使用requests/pymysql和beautifulsoup4爬取维基百科词条链接并存入数据库的更多相关文章
- 从0开始学爬虫9之requests库的学习之环境搭建
从0开始学爬虫9之requests库的学习之环境搭建 Requests库的环境搭建 环境:python2.7.9版本 参考文档:http://2.python-requests.org/zh_CN/l ...
- 从0开始学爬虫4之requests基础知识
从0开始学爬虫4之requests基础知识 安装requestspip install requests get请求:可以用浏览器直接访问请求可以携带参数,但是又长度限制请求参数直接放在URL后面 P ...
- <爬虫>利用BeautifulSoup爬取百度百科虚拟人物资料存入Mysql数据库
网页情况: 代码: import requests from requests.exceptions import RequestException from bs4 import Beautiful ...
- NodeJs简单七行爬虫--爬取自己Qzone的说说并存入数据库
没有那么难的,嘿嘿,说起来呢其实挺简单的,或者不能叫爬虫,只需要将自己的数据加载到程序里再进行解析就可以了,如果说你的Qzone是向所有人开放的,那么就有一个JSONP的接口,这么说来就简单了,也就不 ...
- python+xpath+requests爬取维基百科历史上的今天
import requests import urllib.parse import datetime from lxml import etree fhout = open("result ...
- python爬虫爬取ip记录网站信息并存入数据库
import requests import re import pymysql #10页 仔细观察路由 db = pymysql.connect("localhost",&quo ...
- python简单爬虫 用beautifulsoup爬取百度百科词条
目标:爬取“湖南大学”百科词条并处理数据 需要获取的数据: 源代码: <div class="basic-info cmn-clearfix"> <dl clas ...
- R语言爬虫:爬取百度百科词条
抓取目标:抓取花儿与少年的百度百科中成员信息 url <- "http://baike.baidu.com/item/%E8%8A%B1%E5%84%BF%E4%B8%8E%E5%B0 ...
- 爬虫实战(一) 用Python爬取百度百科
最近博主遇到这样一个需求:当用户输入一个词语时,返回这个词语的解释 我的第一个想法是做一个数据库,把常用的词语和词语的解释放到数据库里面,当用户查询时直接读取数据库结果 但是自己又没有心思做这样一个数 ...
随机推荐
- sort对二维字符数组排序
转载:sort对二维字符数组排序
- linux系统编程综合练习-实现一个小型的shell程序(四)
上节中已经对后台作业进行了简单处理,基本上要实现的功能已经完了,下面回过头来,对代码进行一个调整,把写得不好的地方梳理一下,给代码加入适当的注释,这种习惯其实是比较好了,由于在开发的时候时间都比较紧, ...
- 【2019牛客多校第一场】XOR
题意: 给你一个集合A,里边有n个正整数,对于所有A的.满足集合内元素异或和为0的子集S,问你∑|S| n<=1e5,元素<=1e18 首先可以转化问题,不求∑|S|,而是求每个元素属于子 ...
- CH6303 天天爱跑步
6303 天天爱跑步 0x60「图论」例题 描述 小C同学认为跑步非常有趣,于是决定制作一款叫作<天天爱跑步>的游戏.<天天爱跑步>是一个养成类游戏,需要玩家每天按时上线,完成 ...
- Spring源码窥探之:ImportSelector
1. 编写实现ImportSelector的类 /** * @author 70KG * @Title: SelectImportBean * @Description: * @date 2018/7 ...
- z-tree的使用bug
最近折腾了下z-tree,这个存在一个bug: 新增icon出不来,废话少说上代码: <style type="text/css"> .ztree li span.bu ...
- MySQL中怎么将LIMIT分页优化?
1.语法: *** limit [offset,] rows 一般是用于select语句中用以从结果集中拿出特定的一部分数据. offset是偏移量,表示我们现在 ...
- C# winform Panel 添加 滚动条
Detailed discussion here. Try this instead for 'only' scrolling vertical.(auto scroll needs to be fa ...
- C# 函数参数中的this
先看下面的代码: public static class StringExtension { public static void Foo(this string s) { Console.Write ...
- Docker+GitLab+Jenkins+kubernetes实现DevOps 持续化集成和持续化部署概念图
Docker+GitLab+Jenkins+kubernetes实现DevOps 持续化集成和持续化部署概念图 转载自:原创 IT综合 作者:百联达 时间:2017-05-09 15:48:08 41 ...