【问题标题】:scrap image with request header on beautifulsoup在beautifulsoup 上带有请求标头的剪贴画
【发布时间】:2022-06-13 02:46:22
【问题描述】:

我有废图像的代码:

import requests, base64
from bs4 import BeautifulSoup


baseurl = "https://www.google.com/search?q=cat&sxsrf=APq-WBuyx07rsOeGlVQpTsxLt262WbhlfA:1650636332756&source=lnms&tbm=shop&sa=X&ved=2ahUKEwjQr5HC66f3AhXxxzgGHejKC9sQ_AUoAXoECAIQAw&biw=1920&bih=937&dpr=1"
headers = {"User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:99.0) Gecko/20100101 Firefox/99.0"}

r_images = requests.get(url=baseurl, headers=headers)


soup_for_image = BeautifulSoup(r_images.text, 'html.parser') 
#find product images
productimages = [] 
product_images = soup_for_image.findAll('img')
for item in product_images:
    # print(item['src'])
    if "data:image/svg+xml" not in item['src']:
        productimages.append(item.get('src'))
print(productimages)

如果没有标头也可以,但是如果我使用请求标头,结果将是base64图像。那么有什么方法可以让我用请求标头废弃图像?

【问题讨论】:

  • 你想放一些标题来只从谷歌搜索中获取 data:image/svg+xml 图像吗?
  • 不,我想使用标头,因为我想获取需要请求标头的价格、名称和链接,但是如果我使用它,则 url_image 更改为 base64。如果我要求没有标题,我不能取消价格、名称和链接(到产品)

标签: python web-scraping beautifulsoup


【解决方案1】:

您可以添加 cookie 同意,它可以工作。
也许一些选择器将来会改变。

import requests, base64
from bs4 import BeautifulSoup

baseurl = "https://www.google.com/search?q=cat&sxsrf=APq-WBuyx07rsOeGlVQpTsxLt262WbhlfA:1650636332756&source=lnms&tbm=shop&sa=X&ved=2ahUKEwjQr5HC66f3AhXxxzgGHejKC9sQ_AUoAXoECAIQAw&biw=1920&bih=937&dpr=1"
headers = {"cookie": "CONSENT=YES+cb.20230531-04-p0.en+FX+908"}
result = requests.get(url=baseurl, headers=headers)
soup = BeautifulSoup(result.text, 'html.parser')
allProducts = soup.findAll(class_="u30d4")
number = 0
for product in allProducts:
    name = product.find(class_="rgHvZc")
    if name is not None:
        number += 1
        print("Product number %d:" % number)
        print("Name : " + name.text)
        productLink = product.find('a')
        print("Link: " + productLink["href"][7:])
        img = product.find('img')
        print("Image: " + img["src"])
        price = product.find(class_="HRLxBb")
        print("Price " + price.text)

希望我能帮到你。

【讨论】:

  • 它确实解决了我的问题
  • 你能给我参考一下吗?
  • 抱歉没有参考资料,我只是在一家刮板公司工作;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-29
  • 2017-08-31
  • 1970-01-01
  • 1970-01-01
  • 2018-09-10
相关资源
最近更新 更多