一步一步分析并爬取我要个性网上的头像
1、发现页面规律
~~~~~~~~
网站:https://www.woyaogexing.com/
~~~~~~~~
打开该网站如图所示可以看到很多分类,我们需要爬取头像所以点到头像这个选项上,我选的是:卡通动漫头像->男生,如下图所示:
~~~~~~~~
页面往下拉有:首页、下一页等选项,点首页可以看到浏览器的地址栏变化变为了https://www.woyaogexing.com/touxiang/z/ktnan/index.html https://www.woyaogexing.com/touxiang/z/ktnan/index_2.html,继续点下一页又变为了https://www.woyaogexing.com/touxiang/z/ktnan/index_3.html,现在我们发现了页面的规律。
分析页面源码
分析首页
回到首页选项,打开浏览器的开发者选项,以谷歌浏览器为例:右键->检查
~~~~~~~~
如上图所示,查看网页的源代码可以发现:div节点的txList就代表着一个头像组,该节点下的a节点里的href就是页面链接,我们拼接一下链接看一下是不是** https://www.woyaogexing.com/touxiang/katong/2019/774709.html 打开这个网址可以看到,如上图所示果然是第一个页面,我们就可以使用此规律使用bs4来提取该页面下所有的头像组子链接。 ![加粗样式](https://i-blog.csdnimg.cn/blog_migrate/4649d1e1510cba1711f9e6ee4d02bd4b.png)
分析子页
下面开始分析最终的头像页面:https://www.woyaogexing.com/touxiang/katong/2019/774709.html 如上图所以,我们发现了li这个节点下,class=“tx-img”,后面的href就是该头像的网址,只不过是没有https,以此为规律我们就可以使用bs4很方便的提取出图片链接。 ![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e4e93c60459de5a7ba2db33a8292ea25.png)
完整代码
import os
import re
import requests
from bs4 import BeautifulSoup
def download(url):
context = get_page(url, is_image=True)
fname = re.match('^https.*/(.*?)$', url)
if fname:
fname = os.path.join('download', fname.group(1))
print('download: {}'.format(fname))
with open(fname, 'wb') as f:
f.write(context)
def get_page(url, is_image=False):
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36"
}
try:
response = requests.get(url, headers=headers)
if response.text or response.content:
if is_image:
return response.content
else:
return response.text
return None
except requests.RequestException:
return None
def get_image_url(html):
bloggers = []
soup = BeautifulSoup(html, 'lxml')
for sublink in soup.find_all('div', class_='txList'):
bloggers.append('https://www.woyaogexing.com' + str(sublink.a['href']))
print(bloggers)
for url in bloggers:
blogger_html = get_page(url)
soup = BeautifulSoup(blogger_html, 'lxml')
for image_link in soup.find_all(name='li', class_='tx-img'):
image_url = 'https:' + image_link.a['href']
download(image_url)
if __name__ == "__main__":
PAGES = 10 # 下载多少页
for i in range(PAGES):
if i < 2:
url = 'https://www.woyaogexing.com/touxiang/z/ktnan/index.html'
else:
url = 'https://www.woyaogexing.com/touxiang/z/ktnan/index_{}.html'.format(i)
html = get_page(url)
get_image_url(html)
效果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/80877b948d338bbd86453710565cdd85.png)
ends…
|