使用 bash,如何从 html 文件中提取特定图像的 URL 和标题文本?

使用 bash,如何从 html 文件中提取特定图像的 URL 和标题文本?

给定数百个按数字排序的 html 文件,每个文件都有多个图像标签,但只有一个图像具有我要查找的 id 并遵循惯例

<img title="$titleText" src="$imgURL" id="foo" border="0" />

其中$imgURL$titleText对于每个页面都是唯一的,并且不可预测,因为页面的URL是(可预测的),并且我想要在每个页面上的图像都有id="foo"(每个页面上相同,其他图像具有不同的或没有ID)。

我该如何提取$imgURL$titleText字符串bash

到目前为止,我正在寻找一个起点

for count in `seq 1 400`; 
   do page="https://website/$count.html"; 
   imgURL=[somehow get $imgURL from $page];
   titleText=[somehow get $titleText from $page];
   echo -e "$count\n$titleText\n$imgURL\n\n" >> some-file; 
done

但对于如何完成括号内的部分却一无所知。
它可能至少需要涉及两个sed/ grep/ curl/ wget

编辑:95% 的答案由 JoW 在下面回答,最后几个细节如下

在 JoW 为我指明了正确的方向后,我能够轻松地弄清楚其余部分。最终使用的脚本与上面的“起点” bash 代码具有相同的预期效果,即:

#!/usr/bin/python
#
from bs4 import BeautifulSoup
import requests
for count in xrange(1, 400):
    ct = str(count)
    url = "website/" + ct + ".html"
    data = requests.get("https://" +url)
    soup = BeautifulSoup(data.text)
    for link in soup.findAll("img", {"id": "foo"}):
        with open('some-file', "a") as out:
            out.write(ct + "\n" + link['title'] + "\n" + link['src'] + "\n\n")

答案1

我最近也遇到了类似的问题,经过无数个小时的挫折,我最终使用了带有 BeautifulSoup4 的 Python,我应该从一开始就使用它——我认为你也应该这样做。它使用起来要容易得多,因为它实际上是为这种类型的练习(即解析 HTML)而构建的。你可以使用 BS4 轻松编写 Python 脚本,将所有图像 URL 收集到一个文件中,然后从 bash 调用该脚本。

这就是我要做的。

编辑:

以下是一个简单示例:

#!/bin/python

from bs4 import BeautifulSoup

soup = BeautifulSoup(open("index.html")) 

for link in soup.findAll("img", {"id": "foo"})
  print(link['src'])

显然,这只会检查一个文件(index.html)并打印指向 stoud 的链接。为了达到您的目的,您可以用 python 编写整个内容(即循环遍历此处的文件)或将文件名从 bash 传递到您的 python 脚本。无论如何,您可能希望将 URL 写入输出文件。

with open('output.txt', 'a') as out:
 out.write(link['src'])

相关内容