如何用Python爬取数据?

2024-05-17 20:11

1. 如何用Python爬取数据?

方法/步骤


在做爬取数据之前,你需要下载安装两个东西,一个是urllib,另外一个是python-docx。

请点击输入图片描述
然后在python的编辑器中输入import选项,提供这两个库的服务

请点击输入图片描述
urllib主要负责抓取网页的数据,单纯的抓取网页数据其实很简单,输入如图所示的命令,后面带链接即可。

请点击输入图片描述
抓取下来了,还不算,必须要进行读取,否则无效。

请点击输入图片描述
5
接下来就是抓码了,不转码是完成不了保存的,将读取的函数read转码。再随便标记一个比如XA。

请点击输入图片描述
6
最后再输入三句,第一句的意思是新建一个空白的word文档。
第二句的意思是在文档中添加正文段落,将变量XA抓取下来的东西导进去。
第三句的意思是保存文档docx,名字在括号里面。

请点击输入图片描述
7
这个爬下来的是源代码,如果还需要筛选的话需要自己去添加各种正则表达式。

如何用Python爬取数据?

2. 如何用python爬取一本书的评论用户

京东图书评论有非常丰富的信息,这里面就包含了购买日期、书名、作者、好评、中评、差评等等。以购买日期为例,使用Python + Mysql的搭配进行实现,程序不大,才100行。相关的解释我都在程序里加注了:
from selenium import webdriver
from bs4 import BeautifulSoup
import re
import win32com.client
import threading,time
import MySQLdb
def mydebug():
driver.quit()
exit(0)
def catchDate(s):
"""页面数据提取"""
soup = BeautifulSoup(s)
z = []
global nowtimes
m = soup.findAll("div",class_="date-buy")
for obj in m:
try:
tmp = obj.find('br').contents
except Exception, e:
continue
if(tmp != ""):
z.append(tmp)
nowtimes += 1
return z
def getTimes(n,t):
"""获取当前进度"""
return "当前进度为:" + str(int(100*n/t)) + "%"
#———————————————————————————————————| 程序开始 |—————————————————————————————————
#确定图书大类
cate = {"3273":"历史","3279":"心理学","3276":"政治军事","3275":"国学古籍","3274":"哲学宗教","3277":"法律","3280":"文化","3281":"社会科学"}
#断点续抓
num1 = input("bookid:")
num2 = input("pagenumber:")
#生成图书大类链接,共需17355*20 = 347100次
totaltimes = 347100.0
nowtimes = 0
#开启webdirver的PhantomJS对象
#driver = webdriver.PhantomJS()
driver = webdriver.Ie('C:\Python27\Scripts\IEDriverServer')
#driver = webdriver.Chrome('C:\Python27\Scripts\chromedriver')
#读出Mysql中的评论页面,进行抓取
# 连接数据库 
try:
conn = MySQLdb.connect(host='localhost',user='root',passwd='',db='jd')
except Exception, e:
print e
sys.exit()
# 获取cursor对象
cursor = conn.cursor()
sql = "SELECT * FROM booknew ORDER BY pagenumber DESC"
cursor.execute(sql)
alldata = cursor.fetchall()
flag = 0
flag2 = 0
# 如果有数据返回就循环输出,htt/review/10178500-1-154.html
if alldata:
for rec in alldata:
#rec[0]--bookid,rec[1]--cateid,rec[2]--pagenumber
if(rec[0] != str(num1) and flag == 0):
continue
else:
flag = 1
for p in range(num2,rec[2]):
if(flag2 == 0):
num2 = 0
flag2 = 1
p += 1
link = "htteview/" + rec[0] + "-1-" + str(p) + ".html"
#抓网页
driver.get(link)
html = driver.page_source
#抓评论
buydate = catchDate(html)
#写入数据库
for z in buydate:
sql = "INSERT INTO ljj (id, cateid, bookid, date) VALUES (NULL, '" + rec[0] + "','" + rec[1] + "','" + z[0] + "');"
try:
cursor.execute(sql)
except Exception, e:
print e
conn.commit()
print getTimes(nowtimes,totaltimes)
driver.quit()
cursor.close()
conn.close()
   京东图书评论有非常丰富的信息,这里面就包含了购买日期、书名、作者、好评、中评、差评等等。以购买日期为例,使用Python + Mysql的搭配进行实现,程序不大,才100行。相关的解释我都在程序里加注了:
from selenium import webdriver
from bs4 import BeautifulSoup
import re
import win32com.client
import threading,time
import MySQLdb
def mydebug():
driver.quit()
exit(0)
def catchDate(s):
"""页面数据提取"""
soup = BeautifulSoup(s)
z = []
global nowtimes
m = soup.findAll("div",class_="date-buy")
for obj in m:
try:
tmp = obj.find('br').contents
except Exception, e:
continue
if(tmp != ""):
z.append(tmp)
nowtimes += 1
return z
def getTimes(n,t):
"""获取当前进度"""
return "当前进度为:" + str(int(100*n/t)) + "%"
#———————————————————————————————————| 程序开始 |—————————————————————————————————
#确定图书大类
cate = {"3273":"历史","3279":"心理学","3276":"政治军事","3275":"国学古籍","3274":"哲学宗教","3277":"法律","3280":"文化","3281":"社会科学"}
#断点续抓
num1 = input("bookid:")
num2 = input("pagenumber:")
#生成图书大类链接,共需17355*20 = 347100次
totaltimes = 347100.0
nowtimes = 0
#开启webdirver的PhantomJS对象
#driver = webdriver.PhantomJS()
driver = webdriver.Ie('C:\Python27\Scripts\IEDriverServer')
#driver = webdriver.Chrome('C:\Python27\Scripts\chromedriver')
#读出Mysql中的评论页面,进行抓取
# 连接数据库 
try:
conn = MySQLdb.connect(host='localhost',user='root',passwd='',db='jd')
except Exception, e:
print e
sys.exit()
# 获取cursor对象
cursor = conn.cursor()
sql = "SELECT * FROM booknew ORDER BY pagenumber DESC"
cursor.execute(sql)
alldata = cursor.fetchall()
flag = 0
flag2 = 0
# 如果有数据返回就循环输出,httreview/10178500-1-154.html
if alldata:
for rec in alldata:
#rec[0]--bookid,rec[1]--cateid,rec[2]--pagenumber
if(rec[0] != str(num1) and flag == 0):
continue
else:
flag = 1
for p in range(num2,rec[2]):
if(flag2 == 0):
num2 = 0
flag2 = 1
p += 1
link = "ht.com/review/" + rec[0] + "-1-" + str(p) + ".html"
#抓网页
driver.get(link)
html = driver.page_source
#抓评论
buydate = catchDate(html)
#写入数据库
for z in buydate:
sql = "INSERT INTO ljj (id, cateid, bookid, date) VALUES (NULL, '" + rec[0] + "','" + rec[1] + "','" + z[0] + "');"
try:
cursor.execute(sql)
except Exception, e:
print e
conn.commit()
print getTimes(nowtimes,totaltimes)
driver.quit()
cursor.close()
conn.close()
   

3. python怎样抓取网页中的文字和数字数据

以下代码在 py2 下运行通过:
import urllib2req = urllib2.Request('https://www.baidu.com/')  # 创建一个 Requset 对象response = urllib2.urlopen(req)  # 调用 urlopenthe_page = response.read()  # 返回一个 response 对象 在 response 中调用 read()print the_page
运行效果:

python怎样抓取网页中的文字和数字数据

4. 如何用python抓取网页上的数据

使用内置的包来抓取,就是在模仿浏览器访问页面,再把页面的数据给解析出来,也可以看做是一次请求。

5. 如何用python爬取豆瓣读书的数据

这两天爬了豆瓣读书的十万条左右的书目信息,用时将近一天,现在趁着这个空闲把代码总结一下,还是菜鸟,都是用的最简单最笨的方法,还请路过的大神不吝赐教。第一步,先看一下我们需要的库:
import requests                       #用来请求网页from bs4 import BeautifulSoup         #解析网页import time          #设置延时时间,防止爬取过于频繁被封IP号import re            #正则表达式库import pymysql       #由于爬取的数据太多,我们要把他存入MySQL数据库中,这个库用于连接数据库import random        #这个库里用到了产生随机数的randint函数,和上面的time搭配,使爬取间隔时间随机
这个是豆瓣的网址:x-sorttags-all我们要从这里获取所有分类的标签链接,进一步去爬取里面的信息,代码先贴上来:
import requestsfrom bs4 import BeautifulSoup       #导入库url="httom/tag/?icn=index-nav"wb_data=requests.get(url)                #请求网址soup=BeautifulSoup(wb_data.text,"lxml")  #解析网页信息tags=soup.select("#content > div > div.article > div > div > table > tbody > tr > td > a")#根据CSS路径查找标签信息,CSS路径获取方法,右键-检查-copy selector,tags返回的是一个列表for tag in tags:tag=tag.get_text()    #将列表中的每一个标签信息提取出来helf="hom/tag/"#观察一下豆瓣的网址,基本都是这部分加上标签信息,所以我们要组装网址,用于爬取标签详情页url=helf+str(tag)print(url)    #网址组装完毕,输出
以上我们便爬取了所有标签下的网址,我们将这个文件命名为channel,并在channel中创建一个channel字符串,放上我们所有爬取的网址信息,等下爬取详情页的时候直接从这里提取链接就好了,如下:
channel='''tag/程序'''
现在,我们开始第二个程序。

QQ图片20160915233329.png
标签页下每一个图片的信息基本都是这样的,我们可以直接从这里提取到标题,作者,出版社,出版时间,价格,评价人数,以及评分等信息(有些外国作品还会有译者信息),提取方法与提取标签类似,也是根据CSS路径提取。我们先用一个网址来实验爬取:
url="htt/tag/科技"wb_data = requests.get(url)soup = BeautifulSoup(wb_data.text.encode("utf-8"), "lxml")tag=url.split("?")[0].split("/")[-1]    #从链接里面提取标签信息,方便存储detils=soup.select("#subject_list > ul > li > div.info > div.pub")  #抓取作者,出版社信息,稍后我们用spite()函数再将他们分离出来scors=soup.select("#subject_list > ul > li > div.info > div.star.clearfix > span.rating_nums")   #抓取评分信息persons=soup.select("#subject_list > ul > li > div.info > div.star.clearfix > span.pl")    #评价人数titles=soup.select("#subject_list > ul > li > div.info > h2 > a")   #书名#以上抓取的都是我们需要的html语言标签信息,我们还需要将他们一一分离出来for detil,scor,person,title in zip(detils,scors,persons,titles):#用一个zip()函数实现一次遍历#因为一些标签中有译者信息,一些标签中没有,为避免错误,所以我们要用一个try来把他们分开执行try:author=detil.get_text().split("/",4)[0].split()[0]     #这是含有译者信息的提取办法,根据“/”  把标签分为五部分,然后依次提取出来yizhe= detil.get_text().split("/", 4)[1]publish=detil.get_text().split("/", 4)[2]time=detil.get_text().split("/", 4)[3].split()[0].split("-")[0]   #时间我们只提取了出版年份price=ceshi_priceone(detil)        #因为价格的单位不统一,我们用一个函数把他们换算为“元”scoe=scor.get_text() if True else ""    #有些书目是没有评分的,为避免错误,我们把没有评分的信息设置为空person=ceshi_person(person)      #有些书目的评价人数显示少于十人,爬取过程中会出现错误,用一个函数来处理title=title.get_text().split()[0]   #当没有译者信息时,会显示IndexError,我们分开处理except IndexError:try:author=detil.get_text().split("/", 3)[0].split()[0]yizhe=""         #将detil信息划分为4部分提取,译者信息直接设置为空,其他与上面一样publish=detil.get_text().split("/", 3)[1]time=detil.get_text().split("/", 3)[2].split()[0].split("-")[0]price=ceshi_pricetwo(detil)scoe=scor.get_text() if True else ""person=ceshi_person(person)title=title.get_text().split()[0]except (IndexError,TypeError):continue   #出现其他错误信息,忽略,继续执行(有些书目信息下会没有出版社或者出版年份,但是数量很少,不影响我们大规模爬取,所以直接忽略)except TypeError:continue#提取评价人数的函数,如果评价人数少于十人,按十人处理def ceshi_person(person):try:person = int(person.get_text().split()[0][1:len(person.get_text().split()[0]) - 4])except ValueError:person = int(10)return person#分情况提取价格的函数,用正则表达式找到含有特殊字符的信息,并换算为“元”def ceshi_priceone(price):price = detil.get_text().split("/", 4)[4].split()if re.match("USD", price[0]):price = float(price[1]) * 6elif re.match("CNY", price[0]):price = price[1]elif re.match("\A$", price[0]):price = float(price[1:len(price)]) * 6else:price = price[0]return pricedef ceshi_pricetwo(price):price = detil.get_text().split("/", 3)[3].split()if re.match("USD", price[0]):price = float(price[1]) * 6elif re.match("CNY", price[0]):price = price[1]elif re.match("\A$", price[0]):price = float(price[1:len(price)]) * 6else:price = price[0]return price
实验成功后,我们就可以爬取数据并导入到数据库中了,以下为全部源码,特殊情况会用注释一一说明。
import requestsfrom bs4 import BeautifulSoupimport timeimport reimport pymysqlfrom channel import channel   #这是我们第一个程序爬取的链接信息import randomdef ceshi_person(person):try:person = int(person.get_text().split()[0][1:len(person.get_text().split()[0]) - 4])except ValueError:person = int(10)return persondef ceshi_priceone(price):price = detil.get_text().split("/", 4)[4].split()if re.match("USD", price[0]):price = float(price[1]) * 6elif re.match("CNY", price[0]):price = price[1]elif re.match("\A$", price[0]):price = float(price[1:len(price)]) * 6else:price = price[0]return pricedef ceshi_pricetwo(price):price = detil.get_text().split("/", 3)[3].split()if re.match("USD", price[0]):price = float(price[1]) * 6elif re.match("CNY", price[0]):price = price[1]elif re.match("\A$", price[0]):price = float(price[1:len(price)]) * 6else:price = price[0]return price#这是上面的那个测试函数,我们把它放在主函数中def mains(url):wb_data = requests.get(url)soup = BeautifulSoup(wb_data.text.encode("utf-8"), "lxml")tag=url.split("?")[0].split("/")[-1]detils=soup.select("#subject_list > ul > li > div.info > div.pub")scors=soup.select("#subject_list > ul > li > div.info > div.star.clearfix > span.rating_nums")persons=soup.select("#subject_list > ul > li > div.info > div.star.clearfix > span.pl")titles=soup.select("#subject_list > ul > li > div.info > h2 > a")for detil,scor,person,title in zip(detils,scors,persons,titles):l = []  #建一个列表,用于存放数据try:author=detil.get_text().split("/",4)[0].split()[0]yizhe= detil.get_text().split("/", 4)[1]publish=detil.get_text().split("/", 4)[2]time=detil.get_text().split("/", 4)[3].split()[0].split("-")[0]price=ceshi_priceone(detil)scoe=scor.get_text() if True else ""person=ceshi_person(person)title=title.get_text().split()[0]except IndexError:try:author=detil.get_text().split("/", 3)[0].split()[0]yizhe=""publish=detil.get_text().split("/", 3)[1]time=detil.get_text().split("/", 3)[2].split()[0].split("-")[0]price=ceshi_pricetwo(detil)scoe=scor.get_text() if True else ""person=ceshi_person(person)title=title.get_text().split()[0]except (IndexError,TypeError):continue   except TypeError:continuel.append([title,scoe,author,price,time,publish,person,yizhe,tag])#将爬取的数据依次填入列表中sql="INSERT INTO allbooks values(%s,%s,%s,%s,%s,%s,%s,%s,%s)"  #这是一条sql插入语句cur.executemany(sql,l)   #执行sql语句,并用executemary()函数批量插入数据库中conn.commit()#主函数到此结束# 将Python连接到MySQL中的python数据库中conn = pymysql.connect( user="root",password="123123",database="python",charset='utf8')cur = conn.cursor()cur.execute('DROP TABLE IF EXISTS allbooks')   #如果数据库中有allbooks的数据库则删除sql = """CREATE TABLE allbooks(title CHAR(255) NOT NULL,scor CHAR(255),author CHAR(255),price CHAR(255),time CHAR(255),publish CHAR(255),person CHAR(255),yizhe CHAR(255),tag CHAR(255))"""cur.execute(sql)  #执行sql语句,新建一个allbooks的数据库start = time.clock()   #设置一个时钟,这样我们就能知道我们爬取了多长时间了for urls in channel.split():urlss=[urls+"?start={}&type=T".format(str(i)) for i in range(0,980,20)]   #从channel中提取url信息,并组装成每一页的链接for url in urlss:mains(url)       #执行主函数,开始爬取print(url)        #输出要爬取的链接,这样我们就能知道爬到哪了,发生错误也好处理time.sleep(int(format(random.randint(0,9))))   #设置一个随机数时间,每爬一个网页可以随机的停一段时间,防止IP被封end = time.clock()print('Time Usage:', end - start)    #爬取结束,输出爬取时间count = cur.execute('select * from allbooks')print('has %s record' % count)       #输出爬取的总数目条数# 释放数据连接if cur:cur.close()if conn:conn.close()
这样,一个程序就算完成了,豆瓣的书目信息就一条条地写进了我们的数据库中,当然,在爬取的过程中,也遇到了很多问题,比如标题返回的信息拆分后中会有空格,写入数据库中会出现错误,所以只截取了标题的第一部分,因而导致数据库中的一些书名不完整,过往的大神如果有什么办法,还请指教一二。等待爬取的过程是漫长而又欣喜的,看着电脑上一条条信息被刷出来,成就感就不知不觉涌上心头;然而如果你吃饭时它在爬,你上厕所时它在爬,你都已经爬了个山回来了它还在爬时,便会有点崩溃了,担心电脑随时都会坏掉(还是穷学生换不起啊啊啊啊~)所以,还是要好好学学设置断点,多线程,以及正则,路漫漫其修远兮,吾将上下而求索~共勉~

如何用python爬取豆瓣读书的数据

6. 如何用python从网页上抓取数据

用Beautiful Soup这类解析模块: Beautiful Soup 是用Python写的一个HTML/XML的解析器,它可以很好的处理不规范标记并生成剖析树(parse tree); 它提供简单又常用的导航(navigating),搜索以及修改剖析树的操作

7. 怎么使用python爬取百度网的数据

Python使用Tensorflow读取CSV数据训练DNN深度学习模型

怎么使用python爬取百度网的数据

8. 如何用python爬取视频网站的数据

1.模拟客户端数据采集,分析http返回结果,清洗需要的数据,入库。
2.根据已有数据进行计算,实现增长率之类的数据计算。
3.实时性很难做,你当然可以不停的采数据回来,做个伪实时系统,但需要考虑这些网站是否做了客户端访问次数的限制,你需要考虑在采集器达到访问次数上限之前所采集的数据能否满足你的要求,否则就要被封IP了。
最新文章
热门文章
推荐阅读