memo-2018_1127_0003
cat index.html | head <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:og="http://opengraphprotocol.org/schema/" xmlns:fb="http://www.facebook.com/2008/fbml" xml:lang="ja" lang="ja"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>トップページ|gihyo.jp … 技術評論社</title> <meta name="description" content="技術評論社提供のIT関連コンテンツサイト" /> <meta name="keywords" content="技術評論社,gihyo.jp," /> <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="Content-Script-Type" content="text/javascript" /> cat index.html | grep 'メールでのお知らせ' <h2><a href="/mail">メールでのお知らせ</a></h2> py scrape_by_lxml.py | grep 'メールでのお知らせ' /mail メールでのお知らせ py scrape_by_bs4.py | grep 'メールでのお知らせ' /mail メールでのお知らせ
#!/usr/bin/env python # coding=utf-8 import lxml.html tree = lxml.html.parse('index.html') html = tree.getroot() for a in html.cssselect('a'): print(a.get('href'), a.text)
#!/usr/bin/env python # coding=utf-8 from bs4 import BeautifulSoup with open('index.html') as f: soup = BeautifulSoup(f, 'html.parser') #print(type(soup.find_all('a'))) # <class 'bs4.element.ResultSet'> #print(type(soup.select('a'))) # <class 'list'> #a = str(soup.find_all('a')) #b= str(soup.select('a')) #print(a==b) # True for a in soup.find_all('a'): print(a.get('href'), a.text) #for a in soup.select('a'): # print(a.get('href'), a.text)
コメント