为什么只抓取20个img标签?

时间:2018-12-04 12:56:51

标签: python-3.x web-scraping beautifulsoup

from urllib.request import Request,urlopen,urlretrieve
import urllib
from bs4 import BeautifulSoup
key = input("Enter the image to be searched \n")
urlpath = "https://www.google.com/search? 
   q="+key+"&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiE9- 
   7LjobfAhXCEHIKHQy6A00Q_AUIDigB&biw=1920&bih=947#imgrc=_"
page_req = Request(urlpath, headers={'User-Agent': 'Mozilla/5.0'})
page= urlopen(page_req).read()
soup =BeautifulSoup(page,'html.parser')
images= soup.find_all('img')
print("Total"+str(len(images)))
image_links=[]
for img in images:
    image_links.append(img.get('src'))
image_count=0
for link in image_links:
    urlretrieve(link,'image_'+str(image_count)+'.jpg')
    image_count+=1

上面的脚本仅从Google图片页面中检测到20个图片标签。为什么它无法检测到网页中的所有图像标签?

2 个答案:

答案 0 :(得分:0)

该URL上的HTML文档仅包含20张图像。

页面加载后,其余部分通过使用JavaScript修改DOM来加载。

答案 1 :(得分:0)

您需要设置更好的User-Agent以获得超过100个

user_agent 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36'
page_req = Request(urlpath, headers={'User-Agent': user_agent})