首先要獲取網頁的代碼,先將其裝成一個函數
def getHTMLText(url): try: r = requests.get(url, timeout = 30) r.raise_for_status() #r.encoding = 'utf-8' return r.text except: return ""
在chrome瀏覽器下,直接進去新聞之后,右鍵題目檢查就可以定位到題目所在的html代碼,如下圖
然后會看到<h1>標簽內,它的上一級標簽是div,並且class="hd",BeautifulSoup提供了一個CSS選擇器,直接調用select方法即可
所以代碼可以寫成
def getContent(url): html = getHTMLText(url) # print(html) soup = BeautifulSoup(html, "html.parser") title = soup.select("div.hd > h1") print(title[0].get_text()) time = soup.select("div.a_Info > span.a_time") print(time[0].string) author = soup.select("div.qq_articleFt > div.qq_toolWrap > div.qq_editor") print(author[0].get_text()) paras = soup.select("div.Cnt-Main-Article-QQ > p.text") for para in paras: if len(para) > 0: print(para.get_text()) print()
完整源代碼
#此代碼主要是從給定騰訊新聞網頁中爬取新聞的題目,時間,正文,作者 import requests from bs4 import BeautifulSoup def getHTMLText(url): try: r = requests.get(url, timeout = 30) r.raise_for_status() #r.encoding = 'utf-8' return r.text except: return "" def getContent(url): html = getHTMLText(url) # print(html) soup = BeautifulSoup(html, "html.parser") title = soup.select("div.hd > h1") print(title[0].get_text()) time = soup.select("div.a_Info > span.a_time") print(time[0].string) author = soup.select("div.qq_articleFt > div.qq_toolWrap > div.qq_editor") print(author[0].get_text()) paras = soup.select("div.Cnt-Main-Article-QQ > p.text") for para in paras: if len(para) > 0: print(para.get_text()) print() #寫入文件 fo = open("text.txt", "w+") fo.writelines(title[0].get_text() + "\n") fo.writelines(time[0].get_text() + "\n") for para in paras: if len(para) > 0: fo.writelines(para.get_text() + "\n\n") fo.writelines(author[0].get_text() + '\n') fo.close() #將爬取到的文章用字典格式來存 article = { 'Title' : title[0].get_text(), 'Time' : time[0].get_text(), 'Paragraph' : paras, 'Author' : author[0].get_text() } print(article) def main(): url = "http://news.qq.com/a/20170504/012032.htm" getContent(url); main()