Last active
December 18, 2017 17:49
-
-
Save acnaman/85716ca7e0b4ca75a85a91625c181e75 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import lxml.html | |
root_url = 'http://localhost:8000/' | |
session = requests.Session() | |
def main() : | |
# メニュー項目を起点としてクローリングする | |
start_url = root_url + 'menu.htm' | |
list_lostlink = makelostlinklist(start_url) | |
if len(list_lostlink) > 0: | |
print("リンク切れしているURLがあります") | |
for link in list_lostlink: | |
print(link) | |
# リンク切れになっているページのリストを作成する | |
def makelostlinklist(start_url) : | |
response = session.get(start_url) | |
ignore_list = [] | |
list_lostlink = [] | |
list_lostlink += checklinks(response, ignore_list) | |
return list_lostlink | |
# リンク切れと思われるページを探す | |
def checklinks(response, ignore_list): | |
root = lxml.html.fromstring(response.content) | |
root.make_links_absolute(response.url) | |
for atag in root.cssselect('a[href]'): | |
url = atag.get('href') | |
# チェック済みのものは無視する | |
if url in ignore_list: | |
continue | |
else: | |
ignore_list.append(url) | |
# スキームがhttp/https以外のものはエラーとなるため除外 | |
if 'http://' in url or 'https://' in url: | |
# ホームページ外のURL→リンク切れをチェックする | |
if root_url not in url: | |
try: | |
res = requests.get(url) | |
# DNSエラーなどでurlにアクセスできない→リンク切れ対象としてカウント | |
except requests.ConnectionError: | |
yield url | |
continue | |
# リンク切れ→リンク切れ対象としてカウント | |
if res.status_code >= 400: | |
yield url | |
# レスポンスが遅いサイト(おまけ。リンク切れの対象にはならない) | |
elif res.elapsed.total_seconds() > 1: | |
print("このリンク先は遅い:" + url) | |
continue | |
#その他(リンク切れ対象外) | |
else: | |
continue | |
# ホームページ内のURL→中にあるリンクを更にたどる | |
else: | |
# リンク内のリンク先を再帰的に探す | |
res = session.get(url) | |
tmplist = [] | |
tmplist += checklinks(res, ignore_list) | |
for url in tmplist: | |
yield url | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment