爬取网址:https://maoyan.com/board/4
会发现榜单一共有10页,每页10部电影,点击下一页观察网址变化,增加了offset参数。当offset=10时,电影排名是21~30.由此知:循环10次,修改offset参数即可爬取到top100的电影名称。
#爬取单个页面,传入参数为网址
def get_one_page(url):
try:
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3423.2 Safari/537.36'
}
response = requests.get(url, headers = headers)
if response.status_code == 200:
return response.text
return None
except RequestException:
return None
def parse_one_page(html):
pattern = re.compile('.*?board-index.*?>(\d+).*?data-src="(.*?)".*?name">(.*?).*?star">(.*?).*?releasetime">(.*?).*?integer">(.*?).*?fraction">(.*?).*? ', re.S)
items = re.findall(pattern, html)
for item in items:
yield{
'index':item[0],
'image':item[1],
'title':item[2].strip(),
'actor':item[3].strip()[3:],
'time':item[4].strip()[5:],
'score':item[5]+item[6]
}
def write_to_file(content):
with open('top100.txt','a',encoding='utf-8') as f:
f.write(json.dumps(content, ensure_ascii=False)+'\n')
传入参数为offset,依次传入十个页面的网址,然后爬取十个页面
def main(offset):
url='https://maoyan.com/board/4?offset='+str(offset)
html=get_one_page(url)
parse_one_page(html)
for item in parse_one_page(html):
print(item)
write_to_file(item)
if __name__=='__main__':
for i in range(10):
main(offset=i*10)
time.sleep(1)
import re
import requests
from requests.exceptions import RequestException
import json
import time
#爬取单个页面,传入参数为网址
def get_one_page(url):
try:
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3423.2 Safari/537.36'
}
response = requests.get(url, headers = headers)
if response.status_code == 200:
return response.text
return None
except RequestException:
return None
#将爬取到的内容用正则表达式提取出来,并且按照字典格式存储
#传入参数为整个页面的内容
def parse_one_page(html):
pattern = re.compile('.*?board-index.*?>(\d+).*?data-src="(.*?)".*?name">(.*?).*?star">(.*?).*?releasetime">(.*?).*?integer">(.*?).*?fraction">(.*?).*? ', re.S)
items = re.findall(pattern, html)
for item in items:
yield{
'index':item[0],
'image':item[1],
'title':item[2].strip(),
'actor':item[3].strip()[3:],
'time':item[4].strip()[5:],
'score':item[5]+item[6]
}
#将爬取到的内容写入文件
#传入参数为处理过后的有效内容
def write_to_file(content):
with open('top100.txt','a',encoding='utf-8') as f:
f.write(json.dumps(content, ensure_ascii=False)+'\n')
def main(offset):
url='https://maoyan.com/board/4?offset='+str(offset)
html=get_one_page(url)
parse_one_page(html)
for item in parse_one_page(html):
print(item)
write_to_file(item)
if __name__=='__main__':
for i in range(10):
main(offset=i*10)
time.sleep(1)
t为延时秒数
__name__=='__main__'
有句话经典的概括了这段代码的意义:
“Make a script both importable and executable”
意思就是说让你写的脚本模块既可以导入到别的模块中用,另外该模块自己也可执行。
——来源:https://www.cnblogs.com/alan-babyblog/p/5147770.html
如果模块是被导入,
__name__
的值为模块名字
如果模块是被直接执行,__name__
的值为__main__
——来源:https://www.cnblogs.com/1204guo/p/7966461.html?tdsourcetag=s_pctim_aiomsg