python爬虫问题
爬取21张图片只有第一张是正确爬取的,其他的爬出来都不是图片,把那些错误的图片改成html格式显示: 安全平台检测到您当前的访问行为存在异常,请稍后重试...源码:
import requests
from bs4 import BeautifulSoup
domain = "https://www.keaidian.com"
"""
注意,
子页面url如果开头是/,直接在前面拼上域名即可
子页面的url不是/开头,此时需要找到主页面url,吧最后一个/后面的东西删掉进行拼接即可
"""
url = "https://www.keaidian.com/gexingtouxiang/6426.html"
resp = requests.get(url)
resp.encoding = 'UTF-8'
n = 1# 图片名称
main_page = BeautifulSoup(resp.text, "html.parser")
a_list = main_page.findAll("a", attrs={"class": "swipebox"})
# print(len(a_list))
for a in a_list:
href = a.get("href")
# print(href)
child_href = domain + a.get("href")
# print(child_href)
# print(href)
# 下载图片
img_scr = requests.get(child_href)
with open(f"D:/pythonxue/text/tupian/{n}.jpg", "wb") as f: # 注意:w是写入文件,需要写成wb
f.write(img_scr.content)
print(f"图片{n}下载完毕")
n += 1
网站应该有反爬机制来防止爬虫抓取,因此您收到了这个提示:“安全平台检测到您当前的访问行为存在异常,请稍后重试...”。
为了解决这个问题,你可以尝试使用User-Agent伪装成一个正常的浏览器访问网站。
同时,你可以使用time.sleep()函数在每次请求之间添加一些延迟以降低爬虫被检测的风险。以下是修改后的代码:
import requests
from bs4 import BeautifulSoup
import time
domain = "https://www.keaidian.com"
url = "https://www.keaidian.com/gexingtouxiang/6426.html"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
}
resp = requests.get(url, headers=headers)
resp.encoding = 'UTF-8'
n = 1
main_page = BeautifulSoup(resp.text, "html.parser")
a_list = main_page.findAll("a", attrs={"class": "swipebox"})
for a in a_list:
href = a.get("href")
child_href = domain + a.get("href")
img_scr = requests.get(child_href, headers=headers)
with open(f"D:/pythonxue/text/tupian/{n}.jpg", "wb") as f:
f.write(img_scr.content)
print(f"图片{n}下载完毕")
n += 1
time.sleep(1)# 增加延迟,可以适当调整这个值
这个代码的主要改动是添加了一个名为headers的字典,其中包含一个User-Agent字符串。
然后在requests.get()函数中添加了headers=headers参数,以将其作为请求头发送。
注意:即使使用了这种方法,仍然存在被检测到的风险。请确保遵守网站的爬虫政策,并在合法的范围内爬取数据。 已解决,在headers加上防盗链就行了
源码:
import requests
from bs4 import BeautifulSoup
import time
domain = "https://www.keaidian.com"
url = "https://www.keaidian.com/gexingtouxiang/6426.html"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3",
#设置防盗链
"Referer": "https://www.keaidian.com/gexingtouxiang/6426.html"
}
resp = requests.get(url, headers=headers)
resp.encoding = 'UTF-8'
n = 1
main_page = BeautifulSoup(resp.text, "html.parser")
a_list = main_page.findAll("a", attrs={"class": "swipebox"})
for a in a_list:
href = a.get("href")
child_href = domain + a.get("href")
img_scr = requests.get(child_href, headers=headers)
with open(f"D:/pythonxue/text/tupian/{n}.jpg", "wb") as f:
f.write(img_scr.content)
print(f"图片{n}下载完毕")
n += 1
time.sleep(10)# 增加延迟,可以适当调整这个值 可以模拟登入淘宝码? workhappymm 发表于 2023-3-17 16:20
可以模拟登入淘宝码?
我是初学者,这个应该是cookie相关的
页:
[1]