Lyi. 发表于 2020-12-14 21:20:08

'str' object has no attribute 'request'

求大神看下怎么修正代码
import urllib.request
import re

def open_url():
    url = 'http://jandan.net/ooxx/MjAyMDEyMTQtOTY=#comments'
    req = urllib.request.Request(url)
    req.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36')
    response = url.request.urlopen(req)
    html = response.read().decode('utf-8')
    return html


def get_img(html):
    p = r'<img src="([^"]+\.jpg)"'
    imglist = re.findall(p,html)
    for each in imglist:
      filename = each.split('/')[-1]
      urllib.request.urlretrieve(each,filename,None)


if __name__ == '__main__':
    get_img(open_url())   




Traceback (most recent call last):
File "D:\爬虫\图片\a.py", line 22, in <module>
    get_img(open_url())
File "D:\爬虫\图片\a.py", line 8, in open_url
    response = url.request.urlopen(req)
AttributeError: 'str' object has no attribute 'request'
>>>

Lyi. 发表于 2020-12-14 21:20:40

{:10_266:}

suchocolate 发表于 2020-12-14 21:27:33

response = urllib.request.urlopen(req)

Lyi. 发表于 2020-12-14 21:41:31

suchocolate 发表于 2020-12-14 21:27


蟹蟹{:10_245:}

Lyi. 发表于 2020-12-14 21:42:42

suchocolate 发表于 2020-12-14 21:27


但是他不下载图片是不是网页链接的问题呢

suchocolate 发表于 2020-12-14 22:29:48

Lyi. 发表于 2020-12-14 21:42
但是他不下载图片是不是网页链接的问题呢

def get_img(html):
    p = r'<img src="([^"]+\.jpg)"'
    imglist = re.findall(p, html)
    for each in imglist:
      url = 'http:' + each
      filename = each.split('/')[-1]
      urllib.request.urlretrieve(url, filename, None)

Lyi. 发表于 2020-12-23 20:10:07

哇哇哇哇哇{:10_279:}
页: [1]
查看完整版本: 'str' object has no attribute 'request'