python3之開發環境PyCharm配置


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')

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM