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. VT-x is not available. (VERR_VMX_NO_VMX) on windows 8

    've installed virtualbox on windows 8 x64, then when I open linux guest machine, I got this error me ...

  2. go http 传递json数据

    上篇博文中简单介绍了Go HTTP的Server 和Client.本文介绍如何在HTTP中传递json格式的数据. Server package main import ( "encodin ...

  3. MongoDB GUI( Robo 3T) Shell使用及操作

    Robo 3T 下载及使用 之前叫 Robomongo,后面被收购了,改名 Robo 3T . 下载链接:https://robomongo.org/download (需要FQ) 安装步骤省略,下一 ...

  4. PHP时间处理

    1.介绍UNIX时间戳 格林威治时间 2.在PHP类中获取日期和时间 time(); getdate()输出数组 3.日期和时间的格式化 date("H-m-d H:i:s",ti ...

  5. android 自定义radiogroup的两种方式

    这里先备注下 listview+radiobutton实现  浅显易懂 http://www.haolizi.net/example/view_3312.html 在radiogoup原生态源码的基础 ...

  6. Linux内存管理和应用

    [作者:byeyear.首发于cnblogs,转载请注明.联系:east3@163.com] 本文对Linux内存管理使用到的一些数据结构和函数作了简要描述,而不深入到它们的内部.对这些数据结构和函数 ...

  7. SpringBoot中实现依赖注入功能

    本文转载自:https://blog.csdn.net/linzhiqiang0316/article/details/52639888 今天给大家介绍一下SpringBoot中是如何实现依赖注入的功 ...

  8. 显式等待大结局___封装成API方便控制层调用

    控制层 测试用例层: 控制层示例代码: #coding=utf-8from selenium.webdriver.common.by import Byfrom selenium.webdriver. ...

  9. 关于 appium get_attribute --获取对应属性值 API说明

    1.获取 content-desc 的方法为 get_attribute("name") ,而且还不能保证返回的一定是 content-desc (content-desc 为空时 ...

  10. java实验五——字符数组、String、StringBuffer的相互转化,StringBuffer的一些方法

    package hello; import java.util.Scanner; public class 实验五 { public static void main(String[] args) { ...