# python實際編寫過程中的問題整理
1. 類型轉換與字符串拼接(+號)字符串替換
存在:int str float 等等 (沒有string函數)
```
itemid = 125845
url = 'http://item.jd.com/' + str(itemid) + '.html'
imgsrc = imgsrc.replace('/n5','/n1')
```
2. 相等是兩個等號 ==
id=123
print(id==123) //true
3. 判斷文件(夾)是否存在,并創建
```
if os.path.exists(filename) == True :
//獲取內容,內容為空則刪除
if len(html) == 0:
os.remove(filename)
if os.path.exists(r'E:\pic')==False:
os.mkdir(r'E:\pic')
```
4. 讀寫文件
```
f = open(filename,'rt',encoding='gbk')
data = f.read()
f.close()
或者用with
with open(filename,'w',encoding='gbk') as f:
f.write(data)
```
5. 發送請求
```
# --------------------------------------------------------
# requests 請求說明
# 請求方式有get/post/put/delete
# 可以傳入的參數有,url,headers,data,timeout,cookies,files等
# url = 'str'
# headers = {'a':'1','b':'2'}
# data = {'a':'1','b':'2'}
# timeout = 3 #單位秒
# cookies = {'a':'1','b':'2'}
# files = {'file': open('/path/a.xls', 'rb')}
# -------------------------------------------------
# 請求結果后面可以跟content|text獲取內容 + decode轉碼
# -------------------------
示例如下:
get_content = requests.get(url='httpxxxx',headers={'User-Agent':'xxx'},timeout=30).text.decode('utf-8)
post_content = requests.post(url='httpxxxx',headers={'User-Agent':'xxx'},data={'a':1,'b':2},timeout=30).text.decode('utf-8)
```
6. 正則用法
```
import re
ress = re.compile(r'url: "(.*)",id').search(txt)
if ress:
print (ress.group())
else:
print ("No match!!")
ress = re.search(r'url: "(.*)",id',txt).group() #返回所有匹配的字符
ress = re.search(r'url: "(.*)",id',txt).group(1) #返回正則括號中匹配的字符
ress = re.search(r'url: "(.*)",id',txt).span() #返回起始結束位置
```
默認search與match都是單行匹配,加flags=re.DOTALL實現多行匹配
`duty = re.search(r'<div class="bmsg job_msg inbox">(.*?)<div', content, flags=re.DOTALL)`
7. soup用法
```
from bs4 import BeautifulSoup
soup = BeautifulSoup(txt, 'lxml')
soup.title.text
soup.find('ul',class_="lh")
soup.find_all('img')
imgurl=[]
for link in soup.find_all('img'):
imgsrc = 'https:'+link.get('src')
imgurl.append(imgsrc)
```
8. 數據庫連接
mongodb
```
pip install pymongo
from pymongo import MongoClient
conn = MongoClient('mongodb://lypeng:jobs89757Aa@119.29.52.50:27017')
db = conn.local
```
9. 線程與進程
10. 圖形化gui編程之tkinter
11. 圖像處理
12. 郵件發送
13.
- 前言
- Interview
- 01-cookie與session
- 04-mysql索引
- 05-memcache與redis
- 06-高并發
- 07-主從同步
- 08-myisam與inondb
- 09-框架區別
- 10-php7新特性
- 11-設計模式
- 12-MySQL優化
- 13-php自動加載機制
- 14-MongoDB命令
- 15-Python爬蟲之scrapy框架
- 16-php運行原理
- 17-單點登錄
- Linux
- linux常見命令
- awk
- sed
- bash-shell
- vim學習教程
- PHP
- php運行機制
- php執行效率
- word2pdf
- php預覽Word
- wechat_wafter2
- Python
- python
- win-bat
- svn操作命令
- git常用操作命令
- git_install
- gitlab安裝
- nextcloud
- docker