# coding=gbk

from bs4 import BeautifulSoup
import requests
import urllib
x = 1
y = 1 def crawl(url):
res = requests.get(url)
soup = BeautifulSoup(res.text, 'html.parser')
global y
with open(f'F:/pachong/xnt/{y}.txt','w',encoding="utf-8") as f:
f.write(str(soup))
y += 1
yinhuns = soup.select('img')
print(yinhuns)
for yh in yinhuns:
print(yh)
link = yh.get('src')
print(link)
global x
urllib.request.urlretrieve(link, f'F:/pachong/xnt/{x}.jpg')
print(f'正在下载第{x}张图片')
x += 1 for i in range(1,5):
url = "https://acg.fi/hentai/23643.htm/" + str(i) try:
crawl(url)
except ValueError as f:
continue
except Exception as e:
print(e)
  • 运行程序过程中返回下面结果
<img alt="A区(ACG.Fi)" class="logo" src="https://acg.fi/logo.png"/>
https://acg.fi/logo.png
HTTP Error 403: Forbidden
  • 问题有三个

    • 搜索src值的时候,没有搜索到全部符合要找的图片网址
    • 返回的第一个网址出现了403错误,拒绝访问
    • soup.select返回的不是正确的list
  • 思考

    • 有可能所要找的网址中包含中文,无法编译
    • 如果通过正则对,请求的url的text进行,筛选
#coding=gbk
from bs4 import BeautifulSoup
import requests
import urllib
x = 1 def crawl(url, header): res = requests.get(url, headers=header)
soup = BeautifulSoup(res.text, 'html.parser') yinhuns = soup.find('div', attrs = {'id':"content-innerText"}).find_all('img',limit=4)
print(yinhuns) for yh in yinhuns: link = yh.get('src')
global x
print(x)
urllib.request.urlretrieve(link, 'F:/pachong/xnt/{}.jpg'.format(x))
print('正在下载第{0}张图片'.format(x))
x += 1 header = {
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaSr 1.0"
}
for i in range(1,5):
url = "https://acg.fi/hentai/23643.htm/" + str(i) try:
crawl(url, header)
except ValueError as f:
continue
except Exception as e:
print(e)
  • 这个过程用了find(),find_all()方法,依旧没有解决list的问题
  • 后续过程使用urllib.parse.quote对中文部分重新编码,但是urllib.request.urlretrieve依然报错
  • 重新修改后
#coding=gbk

import requests
import urllib
import re
from PIL import Image
from io import BytesIO
x = 1 # 获取抓取的图片源网址
def crawl(url, header): res = requests.get(url, headers=header)
# 防止被反爬,打开后关闭
res.close()
res = res.text
pattern = re.compile('http.*?apic.*?jpg')
result = re.findall(pattern, res)
return result # 对重编码的网址下载图片
def down(outs, folder_path):
global x
for out in outs:
# 获取新编码的URL地址
res = requests.get(out)
# 防止被反爬,打开后关闭
res.close()
bf = BytesIO()
bf.write(res.content)
img = Image.open(bf)
print(f'正在下载第{x}张图片')
img.save(folder_path + f"{x}.jpg")
x += 1 # 对获取的图片源网址进行重编码
def bianma(results):
outs = []
for s in results:
# 用正则筛选出中文部分
pattern = re.compile('[\u4e00-\u9fa5]+')
result = re.search(pattern, s)
su = result.group(0)
# 把中文部分重洗编码
li = urllib.parse.quote(su)
# 把原URL地址中文部分替换成编码后的
out = re.sub(pattern, li, s)
outs.append(out)
# 对列表进行去重并且按照原来的次序排列
outs_cp = sorted(set(outs), key=outs.index)
return outs_cp def main():
try:
header = {
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaSr 1.0"
}
folder_path = 'F:/pachong/xnt/'
for i in range(1,5):
url = "https://acg.fi/hentai/23643.htm/" + str(i)
results = crawl(url, header)
outs = bianma(results)
down(outs, folder_path)
except Exception as e:
print(e) if __name__ == '__main__':
main()
  • 对于图片路径中有中文的,可以使用BytesIO和PIL下载图片,证实可以有效解决
  • 几次试验出现[Errno 10054] 远程主机强迫关闭了一个现有的连接,可以在requests.get()后使用close()
  • 程序运行无误,就是有点慢,后期可以使用多线程尝试

爬虫遇到HTTP Error 403的问题的更多相关文章

  1. HTTP Error 403没有了,但是中文全都是乱码。又是怎么回事?

    首先是简单的网页抓取程序: [python] import sys, urllib2req = urllib2.Request("http://blog.csdn.net/nevasun&q ...

  2. urllib.error.HTTPError: HTTP Error 403: Forbidden

    问题:  urllib.request.urlopen() 方法经常会被用来打开一个网页的源代码,然后会去分析这个页面源代码,但是对于有的网站使用这种方法时会抛出"HTTP Error 40 ...

  3. python3 HTTP Error 403:Forbidden

    问题描述初学python,在用python中的urllib.request.urlopen()和urllib.request.urlretrieve方法打开网页时,有些网站会抛出异常: HTTP Er ...

  4. Python "HTTP Error 403: Forbidden"

    问题: 执行下面的语句时 def set_IPlsit(): url = 'https://www.whatismyip.com/' response = urllib.request.urlopen ...

  5. python抓取不得姐动图(报错 urllib.error.HTTPError: HTTP Error 403: Forbidden)

    抓取不得姐动图(报错) # -*- coding:utf-8 -*- #__author__ :kusy #__content__:文件说明 #__date__:2018/7/23 17:01 imp ...

  6. asp.net mvc4 HTTP Error 403.14

    asp.net mvc4项目部署到II&上时,出现HTTP Error 403.14 - Forbidden - The Web server is configured to not lis ...

  7. 解决github push错误The requested URL returned error: 403 Forbidden while accessing

    来源:http://blog.csdn.net/happyteafriends/article/details/11554043 github push错误: git push error: The  ...

  8. 解决git提交问题error: The requested URL returned error: 403 Forbidden while accessing

    git提交代码时,出现这个错误"error: The requested URL returned error: 403 Forbidden while accessing https&qu ...

  9. PYCURL ERROR 22 - "The requested URL returned error: 403 Forbidden"

    RHEL6.5创建本地Yum源后,发现不可用,报错如下: [root@namenode1 html]# yum install gcc Loaded plugins: product-id, refr ...

随机推荐

  1. conntrack-tools使用

    基础用法 系统配置 ### 开启流数据包统计(packets和bytes) # echo "net.netfilter.nf_conntrack_acct=1" >> ...

  2. 51nod1100(计算斜率)

    题目链接:https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1100 题意:中文题啦- 思路:算斜率不用多说吧?本题唯一一个 ...

  3. 洛谷P3645 [APIO2015]雅加达的摩天楼(最短路+分块)

    传送门 这最短路的建图怎么和网络流一样玄学…… 一个最朴素的想法是从每一个点向它能到达的所有点连边,边权为跳的次数,然后跑最短路(然而边数是$O(n^2)$除非自创复杂度比spfa和dijkstra还 ...

  4. 微信分账功能与微信支付企业付款相关内容详解(payjs版)

    PAYJS开通微信分账功能以来,有很多同学咨询相关情况.很多同学关心有没有什么办法,可以让自己的商户号快速开通企业付款功能.这里就介绍下微信分账的具体相关内容,可以完美解决问题. 一.什么是微信分账? ...

  5. 条件分页 分页条件和页参数传递方式一 超链接拼串 方式二 使用查询表单searchForm

    <%-- Created by IntelliJ IDEA. User: jie Date: 2019/5/10 Time: 20:00 To change this template use ...

  6. 从零开始学Docker

    在写这篇博客之前,听说过Docker技术,但是一直没有主动去深入了解.用这篇博客来记录自己学习Docker的个人总结,会一直补充完善. 我这边先随便写,后期再做总结!! Docker官网: https ...

  7. C# Dictionary类型转json方法之一

    using Newtonsoft.Json;//引用命名空间 Dictionary<string, string> Content = new Dictionary<string, ...

  8. 牛客网Java刷题知识点之面向对象java的四大特性(抽象、封装、继承、多态)

    不多说,直接上干货! 面向对象java的四大特性之抽象 抽象就是有点模糊的意思,还没确定好的意思. 就比如,要定义一个方法和类.但还没确定怎么去实现它的具体一点的子方法,那我就可以用抽象类或接口.具体 ...

  9. Python 踩坑之旅进程篇其四一次性踩透 uid euid suid gid egid sgid的坑坑洼洼

    目录 1.1 踩坑案例 1.2 填坑解法 1.3 坑位分析 1.4 技术关键字 1.5 坑后思考 下期坑位预告 代码示例支持 平台: Centos 6.3 Python: 2.7.14 代码示例: 菜 ...

  10. 将SpringBoot默认使用的tomcat替换为undertow

    随着微服务的兴起,越来越多的互联网应用在选择web容器时使用更加轻量的undertow或者jetty.SpringBoot默认使用的容器是tomcat,如果想换成undertow容器,只需修改pom. ...