求教 python 网站爬虫过滤出图片 url 的问题

2016-02-19 09:24:50 +08:00
 Koge

下面代码是在图片网站上截取的,想问下用 Python 爬虫,怎样才能过滤出 images 下面不同 size 的图片 url 呢?

"images": [{
            "size": "watermark",
            "url": "https:\/\/drscdn.500px.org\/photo\/original\/store\/67585293\/m%3D900_k%3D2_b%3D2_dpi%3D300_attachment%3D1_tags%3D1\/e47f93b520c772b2612bef1ff2fa77ae"
        },
        {
            "size": "280",
            "url": "https:\/\/drscdn.500px.org\/photo\/67585293\/w%3D280_s%3D1\/a967861eaf97496c9243c9aaccb63502"
        },
        {
            "size": "560",
            "url": "https:\/\/drscdn.500px.org\/photo\/67585293\/w%3D560_s%3D1\/90e4feec7585c24a5f1d45b1ee21262b"
        },
        {
            "size": "600",
            "url": "https:\/\/drscdn.500px.org\/photo\/67585293\/w%3D600_s%3D1\/aa4e4a084ea37fa1ce8a82c3865ce43a"
        },
        {
            "size": "115",
            "url": "https:\/\/drscdn.500px.org\/photo\/67585293\/w%3D115_h%3D115_s%3D1\/8fae531a821e375dda4f4938b0b5829f"
        },
        {
            "size": "160",
            "url": "https:\/\/drscdn.500px.org\/photo\/67585293\/w%3D160_h%3D160_s%3D1\/0e4a9829237dd66700a27ebed6d8f761"
        },
        {
            "size": "2048",
            "url": "https:\/\/drscdn.500px.org\/photo\/67585293\/w%3D2048\/d8142c223fa99fc99b9bd4a1b44462eb"
        }],
3904 次点击
所在节点    Python
12 条回复
yahoo21cn
2016-02-19 09:30:27 +08:00
正则
mgna17
2016-02-19 09:56:14 +08:00
比如这样么
re.findall(r'(?<=url\":\s\").+?(?=\}\,)', your_text)
jarlyyn
2016-02-19 09:56:34 +08:00
首先,这个明显是 json 的一部分。

其次, 500px 自己就有公开的 api 。
Ncer
2016-02-19 09:56:48 +08:00
这种格式的用 json 解析一下
annielong
2016-02-19 09:59:59 +08:00
明显是 json ,格式化一下后输出就可以了,不用正则吧
popok
2016-02-19 10:19:55 +08:00
@annielong 对, json 直接操作就行,格不格式化只是给自己好看点而已。
magicdawn
2016-02-19 10:28:53 +08:00
拿到 json 字符串, 找到 `"images": [` 左大括号 index, 计算出右大括号 index, slice, json.load
magicdawn
2016-02-19 10:29:07 +08:00
中括号...
Koge
2016-02-19 10:55:14 +08:00
@magicdawn 怎样才能从 html 里面解析并且拿到 json 字符串呢?
imn1
2016-02-19 11:08:56 +08:00
正则执行效率高, json 开发效率高
如果 json 不是单独一个文件或 XHR ,而是嵌入在页面或某个 js 里面,建议还是正则快
Frapples
2016-02-19 11:12:00 +08:00
import json
img_info = json.loads(json_str)
# json_str 就是你抓下来的字符串,从你贴的内容来看是 json 格式的。用此函数解析成 python 的数据结构。
# 然后你可以 print(img_info)看看
mikezhang0515
2016-02-19 11:55:29 +08:00
把\/替换成 / 然后匹配 url

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/257543

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX