一、确定好需要爬取的网站
二、右键检查网页源码,找到所需要爬取的数据所在的位置
通过分析链接可得所需要爬取的数据都在这个页面,并且通过链接可以看到不通的页面page和不通的类型type之间都有差别,可以通过这些差别来爬取不同页面或不同类型的数据。
三、编写代码来爬取数据(这里我只用了最粗糙的代码,便于理解。)
import requests
from lxml import etree
import time
import re
import os
import threading
lists = ['%E5%85%A8%E9%83%A8%E7%B1%BB%E5%9E%8B','%E6%BC%94%E5%87%BA','%E5%B1%95%E8%A7%88','%E6%9C%AC%E5%9C%B0%E7%94%9F%E6%B4%BB']
def get_txt():
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36 SLBrowser/8.0.0.9231 SLBChan/105',
'Cookie': 'HMACCOUNT_BFESS=46935071688D78C1; BDUSS_BFESS=l1SU5nNXJhem5NUUtuUGF3M0tUZFh5V356bE43d3lCc2FQT3dKYThTU1VRMVpqRVFBQUFBJCQAAAAAAAAAAAEAAAACCeP-tv60ztSq1q7N6NfTAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJS2LmOUti5jSW; BAIDUID_BFESS=ADBC15F9539AC3DC4E2B4357892C6338:FG=1; ZFY=0tSY2YREU0sWPj7omdNG8nhw:AMIBJMcSjpUUKTA0:BvE:C; H_PS_PSSID='
}
n = 0
type_project= ''
for type in lists:
n += 1
if n == 1:
type_project = '全部类型'
print("这里是全部类型")
elif n == 2:
type_project = '演出'
print("这里是演出")
elif n == 3:
type_project = '展览'
print("这里是展览")
else:
type_project = '本地生活'
print("这里是本地生活")
for page in range(1,5):
url = ("https://show.bilibili.com/api/ticket/project/listV2?version=134&page={}&pagesize=16&area=-1&filter=&platform=web&p_type={}").format(page,type)
source = requests.get(url=url, headers=headers).content.decode('utf-8').split('project_id')
print('\n这是第{}页\n'.format(page))
if not os.path.isdir('会员购1'): # 判断是否为目录
os.mkdir('会员购1') # 创建一级目录
m = 0
for i in source[1:]:
demo = re.compile('"project_name":"(.*?)"')
m += 1
demo1 = re.compile('"city":"(.*?)"')
demo2 = re.compile('"price_low":([0-9]+)')
demo3 = re.compile('"price_high":([0-9]+)')
demo4 = re.compile('"tlabel":"(.*?)"')
demo5 = re.compile('"venue_name":"(.*?)"')
project_name = ''.join(demo.findall(i)) #不合并是列表,合并是字符串
city = ''.join((demo1.findall(i)))
price_low = ''.join(demo2.findall(i))
price_high = ''.join((demo3.findall(i)))
start_time = ''.join((demo4.findall(i)))
venue_name = ''.join((demo5.findall(i)))
with open('会员购1/{}.txt'.format(type_project),'a',encoding='utf-8') as f: #写成w的话就会覆盖掉之前保留的数据,最终只显示最后一行数据,需要解码才能识别写入
f.write(project_name+"\n"+city+"\n"+price_low+"\n"+price_high+"\n"+start_time+"\n"+venue_name+"\n\n")
f.close()
print('共匹配了{}个项目'.format(m))
thread1 = threading.Thread(name='t1',target= get_txt())
thread1.start()
#这里看起来是用了进程,实际上完全没有显示,不用管这个,就算没有打包成类也可以直接爬取。
四、爬取成功之后就会创建一个会员购1的文件夹来保存这些txt数据,如下:
五、查看爬取到的内容,可以看到信息都已经爬取出来了
文章出处登录后可见!
已经登录?立即刷新