【问题标题】:Get the code from inspect element using Python使用 Python 从检查元素中获取代码
【发布时间】:2014-10-03 08:40:12
【问题描述】:

在Safari浏览器中,我可以右键选择“Inspect Element”,出现很多代码。是否可以使用 Python 获取此代码?最好的解决方案是获取一个包含代码的文件。

更具体地说,我正在尝试在此页面上找到指向图像的链接:http://500px.com/popular。我可以看到“检查元素”中的链接,我想用 Python 检索它们。

【问题讨论】:

  • 您在检查元素中看到的代码是页面源代码,即浏览器获取并转换为可视网站的文本。 chrome的inspect元素为开发人员提供了很多功能,但它的核心仍然只是源代码。当然,您可以使用 python 获取该信息-但您的问题非常笼统-您是要抓取整个网站,单个页面还是要获取其中的特定部分?该页面的样式表呢?
  • 我正在尝试在此页面上找到指向图像的链接:500px.com/popular。我可以看到“检查元素”中的链接,并用 Python 检索它们。
  • 看到了吗?这是一个完全不同的问题!获取网页的源代码需要两行代码:import urllib; urllib.urlopen("http://500px.com/popular").read();。它正在分析通常是复杂部分的html。建议你learn a bit about scraping,开始熟悉python抓取库(如BeautifulSoup
  • 哦,看,500px 有一个 API。所以如果你很懒,还有一个ready-made python client
  • 我试过了,但链接不存在。那么从“检查元素”获取代码不是一个简单的方法吗?

标签: python web mechanize inspect-element


【解决方案1】:

获取网页源代码的一种方法是使用Beautiful Soup library。这方面的教程显示在here。页面中的代码如下所示,cmets 是我的。此特定代码不起作用,因为它用作示例的站点上的内容已更改,但该概念应该可以帮助您做您想做的事情。希望对您有所帮助。

from bs4 import BeautifulSoup
from urllib2 import urlopen

BASE_URL = "http://www.chicagoreader.com"

def get_category_links(section_url):
    # Put the stuff you see when using Inspect Element in a variable called html.
    html = urlopen(section_url).read()    
    # Parse the stuff.
    soup = BeautifulSoup(html, "lxml")    
    # The next two lines will change depending on what you're looking for. This 
    # line is looking for <dl class="boccat">.  
    boccat = soup.find("dl", "boccat")    
    # This line organizes what is found in the above line into a list of 
    # hrefs (i.e. links). 
    category_links = [BASE_URL + dd.a["href"] for dd in boccat.findAll("dd")]
    return category_links

编辑 1:上面的解决方案提供了一种通用的网络抓取方式,但我同意 cmets 的问题。 API 绝对是该网站的必经之路。感谢 yuvi 提供。该 API 可在https://github.com/500px/PxMagic 获得。


编辑 2:有一个关于获取热门照片链接的问题示例。来自example 的 Python 代码粘贴在下面。您需要安装 API 库。

import fhp.api.five_hundred_px as f
import fhp.helpers.authentication as authentication
from pprint import pprint
key = authentication.get_consumer_key()
secret = authentication.get_consumer_secret()

client = f.FiveHundredPx(key, secret)
results = client.get_photos(feature='popular')

i = 0
PHOTOS_NEEDED = 2
for photo in results:
    pprint(photo)
    i += 1
    if i == PHOTOS_NEEDED:
        break

【讨论】:

  • 当我运行时: html = urlopen("500px.com/popular").read(), 我找不到链接.. 与我在浏览器中右键单击并选择“检查元素”的代码不同.
  • @user3465589:链接是由该页面中嵌入的一些 JavaScript 延迟加载的。除非您仅使用 API,否则获取链接将非常困难。老实说。
  • @user3465589 我从 API 作者编写的示例中复制并粘贴了代码。
  • 好的!但是如何安装 API 库..?
  • @user3465589 你没有安装 API,你 use it(在这种情况下 - 你需要下载并使用客户端)
猜你喜欢
  • 2014-03-27
  • 2014-04-16
  • 2014-08-20
  • 1970-01-01
  • 2016-07-07
  • 2014-09-21
  • 1970-01-01
  • 1970-01-01
  • 2015-09-05
相关资源
最近更新 更多