作者craig1122321 (半醉夜猫)
看板Python
标题[问题] 图片爬虫遇到https该如何解决
时间Thu May 11 18:47:15 2017
如题 下方为程式码
import requests ,threading
from bs4 import BeautifulSoup
from urllib.request import urlopen
headers ={
'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36'
}
url = ('
http://www.dcard.tw/f/photography/p/226364232.html')
res = requests.get(url , headers = headers)
soup = BeautifulSoup(res.text, "html.parser")
imgs = soup.select('img')
for img in imgs:
try:
fn = img['src']
print(fn)
img=urlopen(fn)
except Exception as e:
print (e)
continue
with open('./imgs/' + str(fn), 'wb') as f:
f.write(img.read())
上面的url为测试用网址。
我有google爬过文
有看到一种写法是if re.match(r'^https?://(i.)?(m.)?imgur.com', link['href']):
不过因为Dcard的图档是存在src里 不知该如何修改 第一次发文有错误烦请指导
感谢各位大大
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 123.205.57.171
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1494499637.A.4E1.html
1F:→ uranusjr: 你都用 requests 了为什麽还要用 urllib 05/11 22:02
2F:→ zerof: ??? dcard 是走 https, imgur 也没有挡 https 爬虫吧? 05/11 22:33
3F:→ craig1122321: 回一楼 因为res变数的那行需要它 05/12 13:03
4F:→ craig1122321: 回二楼 会出现http error 403 修改後变成OSError 05/12 13:04
5F:→ craig1122321: Error 22 Invalid argument 05/12 13:05
7F:→ zerof: ??? code 跑起来是正常的,无法复制你的 bug, 有 error log? 05/12 14:21
8F:→ craig1122321: Z大 应该这样讲 程式跑起来是正常 不过实际上并没有 05/12 21:41
9F:→ craig1122321: 把图片下载到电脑(Imgs)中 05/12 21:41
10F:→ zerof: ....所以你 imgs/ 里面没东西? 05/12 22:19
11F:→ craig1122321: 是的 请问Z大的可以? 05/12 23:39
12F:推 king4647: dcard 有开放api 满好抓的 05/20 23:46
13F:→ starcaspar: 我觉得名称有斜线在档案上会出问题 06/03 23:23
14F:→ starcaspar: with open('./imgs/' + str(fn.split("/")[-1]) 06/03 23:23
15F:→ starcaspar: (後面自行补齐)开档存档留下最後的档名就好了 06/03 23:24
16F:→ starcaspar: 补:https在repl会出问题,不是code的问题 06/03 23:28