求助:python爬取图片,怎么取出标签里的src内容?

from bs4 import BeautifulSoup

import requests

import os

import lxml

import parsel

headers = {

'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36'

}

url = 'https://www.archdaily.com/946565/higashi-sanchome-toilet-nao-tamura/5f4790beb35765c1ca0000ea-higashi-sanchome-toilet-nao-tamura-photo'

result = requests.get(url, headers= headers)

parse = parsel.Selector(result.text)

targetCode = parse.xpath('/html/body/div[1]/div[1]/div[1]/div/div/div[1]/figure/img')

print(targetCode)

返回的结果

[<Selector xpath='/html/body/div[1]/div[1]/div[1]/div/div/div[1]/figure/img' data='<img class="afd-gal-img js-gal-img" i...'>]

我需要的内容是img标签里的src或是data-largesrc图片地址(两者内容好像一样),试过print(targetCode.extract_first().encode('utf-8'))

但是返回img内容只有一半

b'<img class="afd-gal-img js-gal-img" id="5f4790beb35765c1ca0000ea-higashi-sanchome-toilet-nao-tamura-photo" alt="Higashi Sanchome Toilet / Nao Tamura,\xc2\xa9 Satoshi Nagare, Courtesy of The Nippon Foundation">'

前面有个b不知道是什么东西,然后也不是我要的,用.extract()也不行,折腾好久了,麻烦帮忙解答下,谢谢
图片说明

回答

源码中有包含所有图片url的json对象
图片说明
因此可以使用BeautifulSoup找到该对象,然后利用json模块读取对象中的所有url,爬取的结果展示如下
图片说明
源码如下

from bs4 import BeautifulSoup

import requests

import os

import lxml

import json

headers = {

'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36'

}

url = 'https://www.archdaily.com/946565/higashi-sanchome-toilet-nao-tamura/5f4790beb35765c1ca0000ea-higashi-sanchome-toilet-nao-tamura-photo'

result = requests.get(url, headers= headers)

soup = BeautifulSoup(result.content,'lxml')

json_data = soup.find('div',attrs={'id':'gallery-items'})

figures = json.loads(json_data.get('data-images'))

for figure in figures:

print(figure['url_large'])

以上是 求助:python爬取图片,怎么取出标签里的src内容? 的全部内容, 来源链接: utcz.com/a/41934.html

回到顶部