python爬虫(爬取段子)

python爬取段子

爬取某个网页的段子

第一步

不管三七二十一我们先导入模块

#http://baijiahao.baidu.com/s?id=1598724756013298998&wfr=spider&for=pc  段子所在的网址
import re 
import  requests   #如果没这模块运行CMD pip  install requests
 

第二步

获取网站的内容

#http://baijiahao.baidu.com/s?id=1598724756013298998&wfr=spider&for=pc  段子所在的网址
import re 
import  requests   #如果没这模块运行CMD pip  install requests
 
response = requests.get(http://baijiahao.baidu.com/s?id=1598724756013298998&wfr=spider&for=pc)
data = response.text

第三步

找到段子所在的位置

#http://baijiahao.baidu.com/s?id=1598724756013298998&wfr=spider&for=pc  段子所在的网址
import re 
import  requests   #如果没这模块运行CMD pip  install requests
 
response = requests.get('http://baijiahao.baidu.com/s?id=1598724756013298998&wfr=spider&for=pc')   #这个编辑器的长度关系没法放一行
data = response.text
#按F12选择自己想要的内容所在的位置copy出来
new_list = re.findall('<span class="bjh-p">(.*?)</span></p><p>',data ) # (.*?)是我们要的内容

第四部

保存文件

#http://baijiahao.baidu.com/s?id=1598724756013298998&wfr=spider&for=pc  段子所在的网址
import re 
import  requests   #如果没这模块运行CMD pip  install requests
 
response = requests.get('http://baijiahao.baidu.com/s?id=1598724756013298998&wfr=spider&for=pc')   #这个编辑器的长度关系没法放一行
data = response.text
#按F12选择自己想要的内容所在的位置copy出来
new_list = re.findall('<span class="bjh-p">(.*?)</span></p><p>',data ) # (.*?)是我们要的内容

for a in new_list:
    with open(r'D:\图片\段子.txt', 'a') as fw:
        fw.write(a)
        fw.flush()

猜你喜欢

转载自www.cnblogs.com/pythonywy/p/10856819.html