获取网页内容
用 requests 抓取网页内容只需要一行代码: r = requests.get(url).
代码返回一个 response 对象, 它包含大量有用的属性. 其中最重要的属性是 ok 和 content. 如果请求失败, r.ok 为 False 并且 r.content 包含该错误信息. content 代表一个字节流, 做文本处理时, 你最好将它解码成 utf-8.
| 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 |
>>> r = requests.get('http://www.c2.com/no-such-page') >>> r.ok False >>> print(r.content.decode('utf-8')) <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head> <title>404 Not Found</title> </head><body> <h1>Not Found</h1> <p>The requested URL /ggg was not found on this server.</p> <hr> <address> Apache/2.0.52 (CentOS) Server at www.c2.com Port 80 </address> </body></html> |
如果代码正常返回没有报错, 那 r.content 会包含请求的网页源码(就是"查看源码"所看到的内容).
用 BeautifulSoup 查找元素
下面的 get_page() 函数会获取给定 URL 的网页源码, 然后解码成 utf-8, 最后再将 content 传递给 BeautifulSoup 对象并返回, BeautifulSoup 使用 HTML 解析器进行解析.
| 1 2 3 4 |
def get_page(url): r = requests.get(url) content = r.content.decode('utf-8') return BeautifulSoup(content, 'html.parser') |
我们获取到 BeautifulSoup 对象后, 就可以开始解析所需要的信息了.
BeautifulSoup 提供了很多查找方法来定位网页中的元素, 并可以深入挖掘出嵌套的元素.
Tuts+ 网站包含了很多培训教程, 这里是我的主页. 在每一个页面包含最多12篇教程, 如果你已经获取了12篇的教程, 你就可以进入下一页面了. 每一篇文章都被 <article> 标签包围着. 下面的函数就是发现页面里的所有 article 元素, 然后找到对应的链接, 最后提取出教程的 URL.
| 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 |
page = get_page('https://tutsplus.com/authors/gigi-sayfan') articles = get_page_articles(page) prefix = 'https://code.tutsplus.com/tutorials' for a in articles: print(a[len(prefix):]) Output: building-games-with-python-3-and-pygame-part-5--cms-30085 building-games-with-python-3-and-pygame-part-4--cms-30084 building-games-with-python-3-and-pygame-part-3--cms-30083 building-games-with-python-3-and-pygame-part-2--cms-30082 building-games-with-python-3-and-pygame-part-1--cms-30081 mastering-the-react-lifecycle-methods--cms-29849 testing-data-intensive-code-with-go-part-5--cms-29852 testing-data-intensive-code-with-go-part-4--cms-29851 testing-data-intensive-code-with-go-part-3--cms-29850 testing-data-intensive-code-with-go-part-2--cms-29848 testing-data-intensive-code-with-go-part-1--cms-29847 make-your-go-programs-lightning-fast-with-profiling--cms-29809 |