鍍金池/ 問答/Python/ Python爬取網(wǎng)站,前幾個有數(shù)據(jù),之后返回None?

Python爬取網(wǎng)站,前幾個有數(shù)據(jù),之后返回None?

想獲取廖雪峰python教程網(wǎng)站的內(nèi)容練練手,發(fā)現(xiàn)有的章節(jié)能返回數(shù)據(jù),但到Python基礎(chǔ)這一章開始返回的都是None,沒明白問題出在哪,求教

圖片描述
錯誤如下:

Traceback (most recent call last):
  File "scraping_the_tutorial.py", line 36, in <module>
    get_urls()
  File "scraping_the_tutorial.py", line 34, in get_urls
    parse_url_to_html(a.attrs["href"],a.get_text())
  File "scraping_the_tutorial.py", line 23, in parse_url_to_html
    content = content.get_text()
AttributeError: 'NoneType' object has no attribute 'get_text'

代碼如下:

import requests
from bs4 import BeautifulSoup

# session對象
session = requests.Session()
# 用于表明自己是何瀏覽器以及指定返回數(shù)據(jù)格式
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 \
            (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36",
            "Accept":"text/html,application/xhtml+xml,application/xml;\
                        q=0.9,image/webp,*/*;q=0.8"}

# 要獲取數(shù)據(jù)的網(wǎng)站                
def parse_url_to_html(url,file_name):
    # 通過get(url,headers)函數(shù)來接受返回的數(shù)據(jù)
    req = session.get("https://www.liaoxuefeng.com"+url, headers=headers)
    # 用bs解析便于處理數(shù)據(jù),第二個參數(shù)是何種解析方法
    bsObj = BeautifulSoup(req.text,"html.parser")
    # 獲取教程內(nèi)容,在class為x-wiki-content x-main-content里
    content = bsObj.find("div",{"class":"x-content"})
    # 用str不用getText是因為有時候有None值
    # 上面錯了,是因為服務(wù)器反爬機(jī)制返回HTTP error503
    print(content)
    content = content.get_text()
    # 存到txt文件夾中
    with open("txt/%s.txt" % file_name,'w') as f:
        f.write(content)

def get_urls():
    html = session.get("https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000", \
                        headers=headers)
    bsObj = BeautifulSoup(html.text,"html.parser")
    directory = bsObj.find("ul",{"id":"x-wiki-index"})
    for a in directory.findAll("a",{"class":"x-wiki-index-item"}):
        parse_url_to_html(a.attrs["href"],a.get_text())

if __name__ == "__main__":
    get_urls()
回答
編輯回答
眼雜

https://www.liaoxuefeng.com/w...,訪問的人一多就嗝屁了

2018年7月7日 11:21
編輯回答
冷眸

大概是被發(fā)現(xiàn)是爬蟲然后被封了吧

2017年7月12日 23:04
編輯回答
薄荷糖

應(yīng)該不是這個原因,我用的VPN不同節(jié)點試過很多次,而且每次都是在那個位置就沒數(shù)據(jù)了,css上也沒什么區(qū)別

2017年12月22日 11:31