獲取某站網站列表,不完全代碼

from urllib import request
from bs4 import BeautifulSoup  # Beautiful Soup是一個可以從HTML或XML文件中提取結構化數據的Python庫

# 構造頭文件,模擬瀏覽器訪問
#pgs1=int(input("這個有多少頁:?"))
#pgs=20
#while pgs<=pgs1:#設置循環自動跳頁

#url = "http://feitianwu7.com/forum-206-{}".format(pgs)+".html"
url = "http://feitianwu7.com/forum-206-10.html"
#print (url)
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())
print(soup)

titles = soup.find_all('a', 'z')  # 查找所有a標籤中class='xi2'的語句
print(titles)
# open()是讀寫文件的函數,with語句會自動close()已打開文件
print(titles)
with open(r"D:\Python\test\articles.txt", "w") as file:  # 在磁盤以只寫的方式打開/創建一個名爲 articles 的txt文件
    for title in titles:
        file.write(title.string + '\n')
        file.write(title.get('href') + '\n\n')
    #   pgs=pgs+1
    #   print("正在進行第{}".format(pgs)+"頁操作")

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章