Week1 Lesson3 小猪短租

感想

这是自己的第一个针对真实网页的爬虫,写完真是满满的自豪感。从来没有想过,在这么短的时间里,可以那么快学会如何写爬虫。虽然现在写的还很简单粗糙,但会一直努力下去。

代码

from bs4 import BeautifulSoup
import requests
import json
import random

def gender_finder(lorder_genders_raw):
for lorder_gender_raw in lorder_genders_raw:
lorder_genders = lorder_gender_raw.get('class')
b = ['member_ico']
if lorder_genders == b:
result = 'male'
else:
result = 'female'
return result

def get_information(web_data):
soup = BeautifulSoup(web_data.text, 'lxml')

titles = soup.select('div.pho_info > h4 > em')
addresses = soup.select('div.pho_info > p > span')
prices = soup.select('div.day_l > span')
room_pictures = soup.select('#curBigImage')
lorder_pictures = soup.select('div.member_pic > a > img')
lorder_genders_raw = soup.select('div.member_pic > div')
lorder_names = soup.select('div.w_240 > h6 > a')

lorder_genders = gender_finder(lorder_genders_raw)

for title, address, price, room_picture, lorder_gender, lorder_picture, lorder_name in zip(
        titles, addresses, prices, room_pictures, lorder_genders, lorder_pictures, lorder_names):
    data = {
        'title': title.get_text(),
        'address': address.get_text().strip('\n                                  '),
        'price': price.get_text(),
        'room_picture': room_picture.get('src'),
        'lorder_gender': lorder_gender,
        'lorder_name':lorder_name.get_text(),
        'lorder_picture':lorder_picture.get('src')
    }
return data

def get_url(url_content):
content_data = requests.get(url_content,proxies=random.choice(ips), timeout=6)
soup = BeautifulSoup(content_data.text, 'lxml')
urls_raw = soup.select('#page_list > ul > li > a')
for url in urls_raw:
urls = [url.get('href') for url in urls_raw]
return(urls)

resp = requests.get("http://tor1024.com/static/proxy_pool.txt")
ips_txt = resp.text.strip().split("\n")
ips = []
for i in ips_txt:
try:
k = json.loads(i)
ips.append(k)
except Exception as e:
print(e)

url_contents = ['http://bj.xiaozhu.com/search-duanzufang-p{}-0/'.format(str(i)) for i in range(1,11,1)]
for url_content in url_contents:
urls = get_url(url_content)
for url in urls:
web_data = requests.get(url, proxies=random.choice(ips), timeout=6)
data=get_information(web_data)
print(data)

总结

  • 爬网页一定要记得用代理,用代理,用代理
  • 可以用.strip去掉爬取的信息中不必要的部分
  • 用函数的方式,把程序分成小块写,会比较容易
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Date:2016-9-21update:2016-9-30By:Black Crow 前言: 终于进入到网络页面...
    black_crow阅读 912评论 0 2
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,127评论 19 139
  • 对生活乏 ,对工作乏,对身体乏,对运动乏。
    唐呐番阅读 188评论 0 0
  • 人生若只如初见,何事秋风悲画扇。 --------------由此而始 一直想写点什么,却不知道如...
    DaneOliver阅读 3,163评论 1 5
  • 作:庄远飞 习惯深夜一个人在行走 街上的人少了只剩下我 天黑了才点亮的灯火 照在路上显得多冷漠 深夜车站那个人在等...
    水清秋智阅读 137评论 0 0