4

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

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

4

1 回答 1

5

获取网页源代码的一种方法是使用Beautiful Soup 库此处显示了一个教程。该页面的代码如下所示,评论是我的。此特定代码不起作用,因为它用作示例的站点上的内容已更改,但该概念应该可以帮助您做您想做的事情。希望能帮助到你。

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:上面的解决方案提供了一种通用的网络抓取方式,但我同意对问题的评论。API 绝对是该网站的必经之路。感谢 yuvi 提供。该 API 可在https://github.com/500px/PxMagic获得。


编辑 2:有一个关于获取热门照片链接的问题示例。示例中的 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
于 2014-08-10T10:46:12.373 回答