Python BS4 스타벅스 인터페이스 그림 오류, tfp = open(filename, 'wb') FileNotFoundError: [Errno 2] 해당 파일 없음 또는

    tfp = open(filename, 'wb') FileNotFoundError: [Errno 2] No such file or directory: '美式咖啡(热/冷).jpg'

오류 메시지는 위와 같습니다. 'American Coffee (hot/cold).jpg'의 /가 크롤링 시 폴더로 인식되어 .replace("/","/"를 사용하여 파일 이름을 처리해야 하기 때문입니다. ) 할 수 있다

urllib.request.urlretrieve(img_url,img_file_name.replace("/","/"))

아래와 같이 코드 쇼

import time
import urllib.request
import urllib.parse
from bs4 import BeautifulSoup

url = 'https://www.starbucks.com.cn/menu/'
# 请求头定制
request = urllib.request.Request(url=url)
# 模拟请求响应
response = urllib.request.urlopen(request)
content = response.read().decode('utf-8')
# print(content)
# with open("星巴克.html","w",encoding='utf-8') as op:
#     op.write(content)

# bs4解析
soup = BeautifulSoup(content,'lxml')
# print(soup)
# print(soup.select("li>a>strong"))
# print(soup.select("li>a>strong")[0].string)

# print(open("demo.html"))

# name_list = soup.select(".grid padded-3 product")
name_list = soup.select("ul[class = 'grid padded-3 product'] strong")
img_url_list = soup.select("ul[class = 'grid padded-3 product'] div[style]")
base_url = 'https://www.starbucks.com.cn'
for i in range(len(name_list)):
    # print(str(name_list[i].text)+"-----"+str(img_url_list[i].get('style')))
    img_url = base_url + img_url_list[i].get('style')[len('background-image: url("'):-2]
    img_file_name = name_list[i].text+".jpg"
    # urllib.request.urlretrieve(filename=name_list[i].text,url)
    print(f"{img_url},{img_file_name}")
    urllib.request.urlretrieve(img_url,img_file_name.replace("/","/"))
    # time.sleep(1)

Guess you like

Origin blog.csdn.net/weixin_46310452/article/details/125959745