获取某站网站列表,不完全代码

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)+"页操作")

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