python3之開發環境PyCharm配置
阿新 • • 發佈:2018-11-11
1. 安裝PyCharm(安裝時注意選擇python),地址: https://www.jetbrains.com/pycharm/
2. 安裝python 地址: https://www.python.org/
3. 開啟PyCharm 選單:File->Settings->Project:x->Project Interpreter
4.以爬蟲為例,在上圖搜尋BeautifulSoup並安裝(python3請安裝BeautifulSoup4)
例項原始碼如下,內容來自:https://blog.csdn.net/csdn2497242041/article/details/77170746
from urllib import request from bs4 import BeautifulSoup # Beautiful Soup是一個可以從HTML或XML檔案中提取結構化資料的Python庫 # 構造標頭檔案,模擬瀏覽器訪問 url = "http://www.jianshu.com" headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'} page = request.Request(url, headers=headers) page_info = request.urlopen(page).read().decode('utf-8') # 開啟Url,獲取HttpResponse返回物件並讀取其ResposneBody # 將獲取到的內容轉換成BeautifulSoup格式,並將html.parser作為解析器 soup = BeautifulSoup(page_info, 'html.parser') # 以格式化的形式列印html print(soup.prettify()) titles = soup.find_all('a', 'title') # 查詢所有a標籤中class='title'的語句 ''' # 列印查詢到的每一個a標籤的string和文章連結 for title in titles: print(title.string) print("http://www.jianshu.com" + title.get('href')) ''' # open()是讀寫檔案的函式,with語句會自動close()已開啟檔案 with open(r"F:\Python\articles.txt","w",encoding='utf-8') as file: # 在磁碟以只寫的方式開啟/建立一個名為 articles 的txt檔案 for title in titles: file.write(title.string + '\n') file.write("http://www.jianshu.com" + title.get('href') + '\n\n')