从一个HTML返回所有的图片链接

 
uses mshtml, ActiveX, COMObj, IdHTTP, idURI;

{ .... }

procedure GetImageLinks(AURL: string; AList: TStrings);
var
   IDoc: IHTMLDocument2;
   strHTML: string;
   v: Variant;
   x: Integer;
   ovLinks: OleVariant;
   DocURL: string;
   URI: TidURI;
   ImgURL: string;
   idHTTP: TidHTTP;
begin
   AList.Clear;
   URI := TidURI.Create(AURL);
   try
     DocURL := ’http://’ + URI.Host;
     if URI.Path <> ’/’ then
       DocURL := DocURL + URI.Path;
   finally
     URI.Free;
   end;
   Idoc := CreateComObject(Class_HTMLDocument) as IHTMLDocument2;
   try
     IDoc.designMode := ’on’;
     while IDoc.readyState <> ’complete’ do
       Application.ProcessMessages;
     v       := VarArrayCreate([0, 0], VarVariant);
     idHTTP := TidHTTP.Create(nil);
     try
       strHTML := idHTTP.Get(AURL);
     finally
       idHTTP.Free;
     end;
     v[0] := strHTML;
     IDoc.Write(PSafeArray(System.TVarData(v).VArray));
     IDoc.designMode := ’off’;
     while IDoc.readyState <> ’complete’ do
       Application.ProcessMessages;
     ovLinks := IDoc.all.tags(’IMG’);
     if ovLinks.Length > 0 then
     begin
       for x := 0 to ovLinks.Length - 1 do
       begin
         ImgURL := ovLinks.Item(x).src;
         // The stuff below will probably need a little tweaking
         // Deteriming and turning realtive URLs into absolute URLs
         // is not that difficult but this is all I could come up with
         // in such a short notice.
         if (ImgURL[1] = ’/’) then
         begin
           // more than likely a relative URL so
           // append the DocURL
           ImgURL := DocURL + ImgUrl;
         end
         else
         begin
           if (Copy(ImgURL, 1, 11) = ’about:blank’) then
           begin
             ImgURL := DocURL + Copy(ImgUrl, 12, Length(ImgURL));
           end;
         end;
         AList.Add(ImgURL);
       end;
     end;
   finally
     IDoc := nil;
   end;
end;


// Beispiel:
// Example:
procedure TForm1.Button1Click(Sender: TObject);
begin
   GetImageLinks(’http://www.swissdelphicenter.ch’, Memo1.Lines);
end;

在使用 BeautifulSoup 解析网页时,获取错误图片链接的问题可能由多个因素引起,包括但不限于图片链接的提取逻辑、HTML标签结构的误判、以及库的使用方式等。以下是常见的原因和对应的解决方案: ### 原因与解决方法 1. **图片链接提取逻辑不准确** 在解析网页时,`<img>` 标签中的 `src` 属性可能包含相对路径或动态加载的内容,如果未进行路径补全或筛选,可能会导致链接错误。 - **解决方案**:确保使用完整的 URL,可以通过 `urllib.parse.urljoin()` 来拼接基础 URL 和相对路径。例如: ```python from urllib.parse import urljoin base_url = "https://example.com" img_tag = soup.find("img", {"class": "example"}) img_url = urljoin(base_url, img_tag.get("src")) ``` 这种方法可以有效避免因相对路径导致的错误。 2. **动态加载内容未被捕获** 如果网页中的图片链接是通过 JavaScript 动态加载的,BeautifulSoup 无法直接解析这些内容,因为它只能解析静态 HTML 文本。 - **解决方案**:结合 `Selenium` 或 `Playwright` 等工具模拟浏览器行为,加载完整的网页内容后再进行解析。 3. **未正确过滤图片链接** 有时提取的图片链接可能包含不需要的内容,例如广告图片或其他无关资源。 - **解决方案**:通过更精确的标签属性筛选图片链接,例如使用 `img` 标签的 `class`、`alt` 或 `title` 属性。例如: ```python images = soup.find_all("img", {"alt": "desired_alt_text"}) ``` 4. **BeautifulSoup 使用方式错误** 如果代码中存在拼写错误或使用了错误的类名,也可能导致解析失败。例如,`BeautifulSoup` 类名必须首字母大写,否则会引发 `ImportError` 错误。 - **解决方案**:确保导入和使用 `BeautifulSoup` 时的语法正确,例如: ```python from bs4 import BeautifulSoup ``` 5. **网络请求未设置 User-Agent** 有些网站会检测请求头,如果未设置 `User-Agent`,可能会导致请求被拒绝,从而获取错误的链接或内容。 - **解决方案**:在发送请求时添加 `User-Agent` 头部信息,例如: ```python headers = {"User-Agent": "Mozilla/5.0"} response = requests.get(url, headers=headers) ``` 6. **图片链接包含查询参数或特殊字符** 有些图片链接可能包含复杂的查询参数,或者特殊字符导致解析错误。 - **解决方案**:对链接进行编码处理,使用 `urllib.parse.quote()` 对特殊字符进行转义。 ### 示例代码 以下是一个完整的示例代码,展示了如何正确获取图片链接并避免常见错误: ```python import requests from bs4 import BeautifulSoup from urllib.parse import urljoin def get_image_links(url, base_url): response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') images = soup.find_all("img") image_urls = [urljoin(base_url, img.get("src")) for img in images] return image_urls # 示例调用 base_url = "https://example.com" url = f"{base_url}/images" image_links = get_image_links(url, base_url) print(image_links) ``` ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值