Python爬虫入门级(五)
实现两个小案例: 1> 爬取豆瓣电影的TOP250 2> 爬取电影的资源下载地址
爬取豆瓣电影的TOP250
1、分页爬取数据 2、csv数据加载到本地
import requests,re,csv
f = open("C:\\Users\\Desktop\\tmp\\data.csv",mode="w")
csvw = csv.writer(f)
for n in ['0','25','50','75','100']:
url = "https://movie.douban.com/top250?start="+n+"&filter="
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36"
}
resq = requests.get(url,headers=headers)
page_content = resq.text
obj = re.compile(r'<li>.*?<div class="item">.*? <span class="title">(?P<name>.*?)'
r'</span>.*?<p class="">.*?<br>(?P<year>.*?) .*?'
r'<span class="rating_num" property="v:average">(?P<score>.*?)</span>.*?'
r'<span>(?P<num>.*?)</span>',re.S)
result = obj.finditer(page_content)
for i in result :
dic = i.groupdict()
dic['year'] = dic['year'].strip()
print(dic.values())
csvw.writerow(dic.values())
resq.close()
爬取电影的资源下载地址
1、跳转子链接爬取数据 2、使用Dataframe 查看数据,并加载到本地
import requests,re
df = pd.DataFrame(columns=('mov_name', 'load_url'))
url = "https://dytt89.com/"
resq = requests.get(url,verify=False)
resq.encoding = "gb2312"
obj1 = re.compile(r"2021必看热片.*<ul>(?P<ul>.*?)</ul>",re.S)
obj2 = re.compile(r"<a href='(?P<href>.*?)'",re.S)
obj3 = re.compile(r'◎片 名(?P<mov_name>.*?)<br />.*?<td '
r'style="WORD-WRAP: break-word" bgcolor="#fdfddf"><a href="(?P<load_url>.*?)">',re.S)
result1 = obj1.finditer(resq.text)
child_href_list = []
for i in result1:
ul = i.group('ul')
result2 = obj2.finditer(ul)
for j in result2:
print(url.strip("/") + j.group('href'))
child_href_list.append(url.strip("/") + j.group('href'))
for child_href in child_href_list:
child_resq = requests.get(child_href,verify=False)
child_resq.encoding = "gb2312"
result3 = obj3.finditer(child_resq.text)
for a in result3:
df = df.append([{'mov_name':a.group('mov_name'),'load_url':a.group('load_url')}], ignore_index=True)
resq.close()
df.to_csv("C:\\Users\\Desktop\\tmp\\movie_load_url.csv")
|