import requests

from bs4 import BeautifulSoup

url = 'http://www.baidu.com'
html = requests.get(url)
sp = BeautifulSoup(html.text, 'html.parser')
print(sp)

html_doc = """
<html><head><title>页标题</title></head>

<p class="title"><b>文件标题</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""

from bs4 import BeautifulSoup

sp = BeautifulSoup(html_doc,'html.parser')

print(sp.find('b')) # 返回值:<b>文件标题</b>

print(sp.find_all('a')) #返回值: [<b>文件标题</b>]

print(sp.find_all("a", {"class":"sister"}))

data1=sp.find("a", {"href":"http://example.com/elsie"})
print(data1.text) # 返回值:Elsie

data2=sp.find("a", {"id":"link2"})
print(data2.text) # 返回值:Lacie

data3 = sp.select("#link3")
print(data3[0].text) # 返回值:Tillie

print(sp.find_all(['title','a']))

data1=sp.find("a", {"id":"link1"})
print(data1.get("href")) #返回值: http://example.com/elsie

import requests

from bs4 import BeautifulSoup

url = 'http://www.wsbookshow.com/'
html = requests.get(url)
html.encoding="gbk"

sp=BeautifulSoup(html.text,"html.parser")
links=sp.find_all(["a","img"]) # 同时读取 <a> 和 <img>
for link in links:
href=link.get("href") # 读取 href 属性的值
# 判断值是否为非 None,以及是不是以http://开头
if((href != None) and (href.startswith("http://"))):
print(href)

import requests

from bs4 import BeautifulSoup

url = 'http://www.taiwanlottery.com.tw/'
html = requests.get(url)
sp = BeautifulSoup(html.text, 'html.parser')

data1 = sp.select("#rightdown")
print(data1)

data2 = data1[0].find('div', {'class':'contents_box02'})
print(data2)
print()

data3 = data2.find_all('div', {'class':'ball_tx'})
print(data3)

import requests
from bs4 import BeautifulSoup

url1 = 'http://www.pm25x.com/' #获得主页面链接
html = requests.get(url1) #抓取主页面数据
sp1 = BeautifulSoup(html.text, 'html.parser') #把抓取的数据进行解析

city = sp1.find("a",{"title":"北京PM2.5"}) #从解析结果中找出title属性值为"北京PM2.5"的标签
print(city)
citylink=city.get("href") #从找到的标签中取href属性值
print(citylink)
url2=url1+citylink #生成二级页面完整的链接地址
print(url2)

html2=requests.get(url2) #抓取二级页面数据
sp2=BeautifulSoup(html2.text,"html.parser") #二级页面数据解析
#print(sp2)
data1=sp2.select(".aqivalue") #通过类名aqivalue抓取包含北京市pm2.5数值的标签
pm25=data1[0].text #获取标签中的pm2.5数据
print("北京市此时的PM2.5值为:"+pm25) #显示pm2.5值

import requests,os
from bs4 import BeautifulSoup
from urllib.request import urlopen

url = 'http://www.tooopen.com/img/87.aspx'

html = requests.get(url)
html.encoding="utf-8"

sp = BeautifulSoup(html.text, 'html.parser')

# 建立images目录保存图片
images_dir="E:\\images\\"
if not os.path.exists(images_dir):
os.mkdir(images_dir)

# 取得所有 <a> 和 <img> 标签
all_links=sp.find_all(['a','img'])
for link in all_links:
# 读取 src 和 href 属性内容
src=link.get('src')
href = link.get('href')
attrs=[src,src]
for attr in attrs:
# 读取 .jpg 和 .png 檔
if attr != None and ('.jpg' in attr or '.png' in attr):
# 设置图片文件完整路径
full_path = attr
filename = full_path.split('/')[-1] # 取得图片名
ext = filename.split('.')[-1] #取得扩展名
filename = filename.split('.')[-2] #取得主文件名
if 'jpg' in ext: filename = filename + '.jpg'
else: filename = filename + '.png'
print(attr)
# 保存图片
try:
image = urlopen(full_path)
f = open(os.path.join(images_dir,filename),'wb')
f.write(image.read())
f.close()
except:
print("{} 无法读取!".format(filename))

吴裕雄 实战python编程(3)的更多相关文章

  1. 吴裕雄 实战PYTHON编程(10)

    import cv2 cv2.namedWindow("frame")cap = cv2.VideoCapture(0)while(cap.isOpened()): ret, im ...

  2. 吴裕雄 实战PYTHON编程(9)

    import cv2 cv2.namedWindow("ShowImage1")cv2.namedWindow("ShowImage2")image1 = cv ...

  3. 吴裕雄 实战PYTHON编程(8)

    import pandas as pd df = pd.DataFrame( {"林大明":[65,92,78,83,70], "陈聪明":[90,72,76, ...

  4. 吴裕雄 实战PYTHON编程(7)

    import os from win32com import client word = client.gencache.EnsureDispatch('Word.Application')word. ...

  5. 吴裕雄 实战PYTHON编程(6)

    import matplotlib.pyplot as plt plt.rcParams['font.sans-serif']=['Simhei']plt.rcParams['axes.unicode ...

  6. 吴裕雄 实战PYTHON编程(5)

    text = '中华'print(type(text))#<class 'str'>text1 = text.encode('gbk')print(type(text1))#<cla ...

  7. 吴裕雄 实战PYTHON编程(4)

    import hashlib md5 = hashlib.md5()md5.update(b'Test String')print(md5.hexdigest()) import hashlib md ...

  8. 吴裕雄 实战python编程(2)

    from urllib.parse import urlparse url = 'http://www.pm25x.com/city/beijing.htm'o = urlparse(url)prin ...

  9. 吴裕雄 实战python编程(1)

    import sqlite3 conn = sqlite3.connect('E:\\test.sqlite') # 建立数据库联接cursor = conn.cursor() # 建立 cursor ...

随机推荐

  1. Microsoft Dynamics CRM 2011 面向Internet部署 (IFD) CRM 登录出现会话超时的解决办法

    一.IFD 登录的时候,过了一段时间,会马上出现“您的会话已过期”,怎么解决这个问题呢,可以通过改变这个时间.具体图如二 Link to Dynamics CRM Wiki Home Page 二.S ...

  2. Spring MVC 3.0 深入及对注解的详细讲解[转载]

    http://blog.csdn.net/jzhf2012/article/details/8463783 核心原理 1.       用户发送请求给服务器.url:user.do 2.       ...

  3. 计算机中丢失api-ms-win-crt-runtime-l1-1-0.dll解决办法

    今天开始Python学习之旅,安装配置好Python环境之后,在命令行中输入Python命令,提示“计算机中丢失api-ms-win-crt-runtime-l1-1-0.dll...” 解决办法: ...

  4. string截断

    public static string GetFirstString(string stringToSub, int length)         {            Regex regex ...

  5. fiddler抓包HTTPS请求

    fiddler抓包HTTPS请求 标签: fiddlerhttps抓包 2016-03-29 21:24 23293人阅读 评论(2) 收藏 举报  分类: 不登高山不知天之高也(1)  版权声明:本 ...

  6. 在Windows下使用svn命令行教程及svn命令行的解释

    本文转载自:https://blog.csdn.net/yangxiao2shi/article/details/50719286/ 以前在公司一直使用git,现在的公司改用svn,一时间还真的不知道 ...

  7. ubuntu修改Bash命令行提示符

    用户通过远程登陆,初始的PS1为\s-\v\$, bash为/bin/bash,然后先后执行/etc/profile和~/.bash_profile中的命令. /etc/profile文件中调用执行/ ...

  8. 在HTML标签的事件后面直接写JS代码

    <input type="button" onclick="document.getElementdByTagName('div')[0].innrtHTML='S ...

  9. linux 添加secondary ip

    linux下ip地址除了primary外,还有两种:1. ip alias(子接口)2. secondary ip(辅助ip) 都可在一块物理网卡上添加,alias由ifconfig添加,ifconf ...

  10. PHP-Socket服务端客户端发送接收通信实例详解

    原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://fighter.blog.51cto.com/1318618/1533957 So ...