入门阶段
1.数据爬虫
spider.py : 网页下载、链接提取、数据存储
从douban.txt 文件中的网址得到movie.txt 文件保存提取出的250个电影简介网址
网页的HTML代码:浏览器界面、右键、查看网页源代码
#将豆瓣电影top250的第一页下载
import urllib.request #导入url-lib-request模块
#设置网址
url="https://movie.douban.com/top250"
#http头信息 在HTML中有
header={
"User-Agent":"Mozilla/5.0(Windows NT 10.0;WOW64)"
"AppleWebKit/537.36(KHTML,like Gecko)"
"Chrome/76.0.3809.87 Safair/537.36 SLBrowser/6.0.1.8131"
}
#构造一个Request请求对象
req=urllib.request.Request(url=url,headers=header)
#向豆瓣服务器发起请求, 获取恢复response
response=urllib.request.urlopen(req)
#读取回复并使用UTF-8编码进行解码
print(html)
#获得html网页代码字符串
从HTML中提取出符合条件和规则的网址,要用到正则表达式
#将豆瓣电影top250的第一页下载
import urllib.request #导入url-lib-request模块
#设置网址
url="https://movie.douban.com/top250"
#http头信息 在HTML中有
header={
"User-Agent":"Mozilla/5.0(Windows NT 10.0;WOW64)"
"AppleWebKit/537.36(KHTML,like Gecko)"
"Chrome/76.0.3809.87 Safair/537.36 SLBrowser/6.0.1.8131"
}
#构造一个Request请求对象
req=urllib.request.Request(url=url,headers=header)
#向豆瓣服务器发起请求, 获取恢复response
response=urllib.request.urlopen(req)
#读取回复并使用UTF-8编码进行解码
html=response.read().decode("utf-8")
return html
#调用函数download_html,下载豆瓣top250第一页, 保存至html
html=download_html("https://movie.douban.com/top250")
import re #导入re正则库
#电影介绍页网址的正则表达式
pattern='https://movie.douban.com/subject/[0-9]+/'
#从html中提取全部满足电影介绍页网址pattern的url
urls=re.findall(pattern,html)
urls=set(urls) #通过set集合去重
#打印出提取出的网址数量和具体网址
print("urls count=%d" %(len(urls)))
for url in urls:
print(url)
完整代码:如何获取豆瓣电影前250的电影内容网址
#将豆瓣电影top250的第一页下载
import urllib.request #导入url-lib-request模块
#设置网址
url="https://movie.douban.com/top250"
#http头信息 在HTML中有
header={
"User-Agent":"Mozilla/5.0(Windows NT 10.0;WOW64)"
"AppleWebKit/537.36(KHTML,like Gecko)"
"Chrome/76.0.3809.87 Safair/537.36 SLBrowser/6.0.1.8131"
}
#构造一个Request请求对象
req=urllib.request.Request(url=url,headers=header)
#向豆瓣服务器发起请求, 获取恢复response
response=urllib.request.urlopen(req)
#读取回复并使用UTF-8编码进行解码
html=response.read().decode("utf-8")
return html
#电影介绍页网址提取的功能封装至函数extract_url中
#函数输入html,返回html中提取的url链接
def extract_url(html):
pattern='https://movie.douban.com/subject/[0-9]+/'
urls=re.findall(pattern,html)
return set(urls)
#以读取方式打开豆瓣电影列表文件
file=open('douban.txt','r')
#以写模式打开movie.txt,用来存储提取出的电影介绍页网址
output=open('movie.txt','w')
#将豆瓣中的网址按行读入
lines=file.readlines()
for url in lines:
#遍历每一行url,通过strip函数去掉收尾空字符
url=url.strip()
print(url)#打印url作为调试信息
#调用download_html 获取url对应的html代码
html=download_html(url)
#调用extract_url提取html中的电影介绍页链接网址
urls=extract_url(html)
for url in urls: #遍历url集合
output.write(url +'\n') #将每个url都写入movie文件
file.close()
uotput.close() #关闭文件