【问题标题】:How to search html for a link and print the link using python?如何在 html 中搜索链接并使用 python 打印链接?
【发布时间】:2014-01-24 03:18:31
【问题描述】:

我正在尝试在 python 中编写一个代码,它将在 html 代码中搜索图像链接,我需要找到我的代码 - .我需要找到http://www.darlighting.co.uk/621-large_default/empire-double-wall-bracket-polished-chrome.jpg 部分,无论链接实际上说什么,是否有这样做或者我应该寻找不同的方法?我可以访问标准的 python 模块和 beautifulsoup。

【问题讨论】:

  • 所以您需要在网页上(在 HTML 中)准确找到该图像?不管图片的 URL 是什么?
  • 是的,很抱歉,如果措辞有点奇怪。
  • 要比较来自网页的图像,您可以下载它们并使用compare。或查看question
  • 我不想比较图像并下载它们,我没有要比较的图像,我只需要一种方法让 python 为我找到 URL,然后我可以使用另一个我编写的程序为我下载图像。不过感谢您的回复:)

标签: python html image


【解决方案1】:

Beautiful Soup 文档有很好的“快速入门”部分:http://www.crummy.com/software/BeautifulSoup/bs4/doc/#quick-start

from bs4 import BeautifulSoup as Soup
from urllib import urlopen

url = "http://www.darlighting.co.uk/"
html = urlopen(url).read()
soup = Soup(html)

# find image tag with specific source
the_image_tag = soup.find("img", src='/images/dhl_logo.png')
print type(the_image_tag), the_image_tag
# >>> <class 'bs4.element.Tag'> <img src="/images/dhl_logo.png"/>

# find all image tags
img_tags = soup.find_all("img")
for img_tag in img_tags:
    print img_tag['src']

【讨论】:

    【解决方案2】:

    您可以尝试使用 lxml(http://lxml.de/) 和 xpath (http://en.wikipedia.org/wiki/XPath)

    例如在html中查找图片可以

    import lxml.html
    import requests
    
    html = requests.get('http://www.google.com/').text
    doc = lxml.html.document_fromstring(html)
    images = doc.xpath('//img') # here you can find the element in your case the image
    if images:
        print images[0].get('src') # here I get the src from the first img
    else:
        print "Images not found"
    

    希望对你有所帮助。

    更新:我在没有“:”之前修复了 else

    【讨论】:

    • 我现在正在尝试,但总是找不到图像,我试着让它工作,感谢您的帮助
    • 我更新添加“:”在其他,并测试我得到“/images/srpr/logo9w.png”
    【解决方案3】:
    import httplib
    from lxml import html
    
    #CONNECTION
    url = "www.darlighting.co.uk"
    path = "/"
    conn = httplib.HTTPConnection(url)
    conn.putrequest("GET", path)
    #HERE YOU HEADERS... 
    header = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64)", "Cache-Control": "no-cache"}
    for k, v in header.iteritems():
        conn.putheader(k, v)
    conn.endheaders()
    res = conn.getresponse()
    
    if res.status == 200:
        source = res.read()
    else:
        print res.status
        print res.getheaders()
    
    #EXTRACT
    dochtml = html.fromstring(source)
    for elem, att, link, pos in dochtml.iterlinks():
        if att == 'src': #or 'href'
            print 'elem: {0} || pos {1}: || attr: {2} || link: {3}'.format(elem, pos, att, link)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-12
      • 2021-10-28
      • 2019-10-18
      • 1970-01-01
      • 2014-07-13
      • 2018-01-11
      • 2021-01-25
      • 2016-07-14
      相关资源
      最近更新 更多