我试图用美丽的汤从文章中刮掉图像。它似乎工作,但我无法打开图像。每次我尝试从桌面访问图像时都会出现文件格式错误。任何见解?
timestamp = time.asctime()
# Parse HTML of article, aka making soup
soup = BeautifulSoup(urllib2.urlopen(url).read())
# Create a new file to write content to
txt = open('%s.jpg' % timestamp, "wb")
# Scrape article main img
links = soup.find('figure').find_all('img', src=True)
for link in links:
link = link["src"].split("src=")[-1]
download_img = urllib2.urlopen(link)
txt.write('\n' + "Image(s): " + download_img.read() + '\n' + '\n')
txt.close()
答案 0 :(得分:2)
您正在为每张图片的数据开头附加一个新行和文字,这实际上会破坏它。
此外,您正在将每个图像写入同一个文件,再次破坏它们。
将用于编写文件的逻辑放在循环中,并且不向图像添加任何额外数据,它应该可以正常工作。
# Scrape article main img
links = soup.find('figure').find_all('img', src=True)
for link in links:
timestamp = time.asctime()
txt = open('%s.jpg' % timestamp, "wb")
link = link["src"].split("src=")[-1]
download_img = urllib2.urlopen(link)
txt.write(download_img.read())
txt.close()