Python:使用request重爬Python教程

最近在使用requests库之后,简直拜服这个库啊,简直是神器。跟select方法配合使用,无往而不胜。

几个CSS tips:

  1. 如果button上有class属性的,如:
<button id="ext-eng=1026" class="x-right-button"...>

可以这样写:

css=button.x-right-button

.代表class

  1. 如果class里带的空格,用.来代替空格如:
<button class="x-btn-text module_picker_icon">...

可以这样写:

css=button.x-btn-text.module_picker_icon
  1. 如果想用别的属性值定位,用方括号【属性名=属性值】的方式,如:
<abbr>Abc<abbr/>
css=abbr[title="Abc"]
```
4. 如果button上有id属性的,如:
```
<input id="ag_name" type="text"...>
```
可以这样写:
```
css=input#ag_name 
```
或者这样
```
css=#ag_name
#代表id
```

详细分析可见[这里](http://www.jianshu.com/p/8441de1c2f03)
具体代码如下:
```
#!usr/bin/env  
# -*-coding:utf-8 -*-
import requests
from bs4 import BeautifulSoup as BS
import os
import sys

reload(sys)
sys.setdefaultencoding('utf-8')

sub_folder = os.path.join(os.getcwd(), "liaoxuefeng")
if not os.path.exists(sub_folder):
    os.mkdir(sub_folder)

#you may not need this
proxies = {
  "http": "http://proxy.com:8080/",
  "https": "https://proxy.com:8080/",
}

domain = 'http://www.liaoxuefeng.com'
python27_url = domain + '/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000'

web_data = requests.get(python27_url, proxies=proxies)
soup = BS(web_data.text, "lxml")

link_lists = soup.select("div.x-sidebar-left-content > ul.uk-nav.uk-nav-side > li > a")

article_maps = []
for article in link_lists:
    article_maps.append(article.get("href"))

for i in range(len(article_maps)):
    url_of_each_chapter = domain + article_maps[i]
    # print url_of_each_chapter
    resp = requests.get(url=url_of_each_chapter, proxies=proxies)
    soup = BS(resp.text, "lxml")
    titles = soup.select("div.x-content > h4")

    title_of_each_chapter = ""
    for title in titles:
        title_of_each_chapter += title.get_text().decode('utf-8').replace("/", " ")
    # print title_of_each_chapter
    contents = soup.select("div.x-wiki-content > p")
    content_of_each_chapter = ""
    for content in contents:
        content_of_each_chapter += content.get_text() + "\n"
    filename = sub_folder + "\\" + str(i) + title_of_each_chapter + ".html"
    # print filename
    with open(filename, "wb") as f:
        f.write(content_of_each_chapter)
    f.close()
```
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,523评论 0 17
  • 《ilua》速成开发手册3.0 官方用户交流:iApp开发交流(1) 239547050iApp开发交流(2) 1...
    叶染柒丶阅读 10,980评论 0 11
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,933评论 18 139
  • 步韵相看不厌兄 文/以琳_ 十二疑坟障眼充,今船犹渡古遗风。 千秋迷雾千言异,万代忠魂万念同。 饕餮...
    以琳_阅读 501评论 3 26
  • 今天算是躺床上躺一天了,直接睡到10点多才起床。然后就是打一天游戏,和女朋友连着输了一下午。然后一起看了两部...
    天空蓝上阅读 162评论 0 0