python - 如何在python中使用xpath在源代码中获取图像src url
问题描述
所以,我正在开发一个程序来从网站下载一些图像,我必须以某种方式获取 img 标签的“src”部分。我可以用 selenium 做到这一点,但我必须调整代码,现在我正在使用 BeautifulSoup4 和 lxml。我目前在变量“mystr”中拥有页面(站点)的整个源代码,我想提供一个 xpath 并在该变量中找到该 xpath?可能吗?(可能)我发布这个问题的原因是因为我似乎无法将变量解析为 lxml 并使用它的函数 .xpath()
--阅读问题的更多上下文--我正在从一个 excel 文件(参考值和 url)中读取一些数据,我想打开 url,下载产品图像,然后重命名它以供参考。我可以使用多张图片执行此操作,但是当 url 只有一张图片时,我想使用 xpath 下载图片,我不想再次使用 selenium。
提前致谢。我认为这是对这个问题很重要的代码部分。
try: #Extrair o html
fp = urllib.request.urlopen(links[i])
mybytes = fp.read()
mystr = mybytes.decode("utf8")
fp.close()
except Exception as ex: #Exceção do html
print("Não foi possivel extrair o HTML deste url")
erros.append(i)
continue
try: #Passar para Beautiful soup 4
soup = BeautifulSoup(mystr, "lxml")
#print(mystr, file = open("teste.txt", "a"))
except Exception as ex: # Exceção do Beautiful soup 4
print("Não foi possivel converter o HTML para bs4\n\n" + ex)
erros.append(i)
continue
try: #Navegar até ao DIV dentro do html extraido
main_div = soup.find_all("div", {"id": div_id})
if len(main_div) == 0:
parser = etree.HTMLParser()
tree = etree.parse(mybytes, parser)
#print(tree, file=open("tree.txt", "a"))
#image = tree.xpath('//*[@id="image"]')
image = tree.xpath("/html/body/div[1]/div/div/div/div[1]/div[1]/div[1]/a/img")
print(image[0].tag)
#input("--------------------------------------------------")
except Exception as ex: #Exceção se não existir um div dentro do HTML extraido com o ID fornecido
print("Não existe nenhum DIV com o id fornecidon\n\n" + ex)
erros.append(i)
continue
解决方案
一种BeautifulSoup
方式:
img_src=soup.find("img")["src"]
一种lxml etree
方式:
img_src=tree.xpath('//img')[0].attrib.get('src')
推荐阅读
- angular - 未知错误:错误:没有为“C:\Users\UTKARSH SRIVASTAVA\AppData\Roaming\npm\node_modules\@angular\cli\node_modules\uuid”找到有效的导出主程序
- file - 为什么我在颤动中从 FileUtilsDisplayTime() 中获取先前保存的值?
- visual-studio - 从 VisualStudio 2019 构建脚本访问 system32
- c# - 返回一个包含列表的对象
- python - Discord.py:wait_for('reaction_add') 未按预期工作
- react-native - 元素无效,应为字符串
- c++ - 如何使用根公钥以编程方式验证中间证书签名?
- python - Python 请求模块在 Windows 笔记本电脑上工作,但在 Ubuntu VPS 上不工作
- javascript - 有人知道 JavaScript 中 php 的 `$a['mykey'][] = $a` 的替代方法吗?
- r - 应用分段线性模型多年