เฉลยแบบฝึกหัดการขูดข้อมูลด้วย BeautifulSoup

เฉลยแบบฝึกหัดการขูดข้อมูลด้วย BeautifulSoup#

!pip install beautifulsoup4
Requirement already satisfied: beautifulsoup4 in /usr/local/lib/python3.7/dist-packages (4.6.3)
from bs4 import BeautifulSoup
import requests

Scraping email addresses#

import re
#url = 'https://math.sc.chula.ac.th/en/people/'
url = 'https://www.arts.chula.ac.th/~english/people/'
page = requests.get(url) # string ของ HTML Code
for email in re.findall('[a-zA-Z0-9.]+@[a-zA-Z0-9.]+', page.text):
  print(email)
avery.shane@gmail.com
sani.c@chula.ac.th
crabtree@chula.ac.th
cheunsumon.d@chula.ac.th
ajarnjennychula@gmail.com
jsomjit@chula.ac.th
tapanat.k@chula.ac.th
andrewlobb83@gmail.com
andrewlobb83@gmail.com
subenja.p@chula.ac.th
brptefl@gmail.com
jittima.p@chula.ac.th
proud.s@chula.ac.th
verita.s@chula.ac.th
puckpan.t@chula.ac.th
rwijitsopon@gmail.com
fasyaESL@gmail.com
darintip.c@chula.ac.th
nirada.s@chula.ac.th
justin.da.silva1982@gmail.com
siamharit@yahoo.com
preena.kangkun@gmail.com
mathurin.l@chula.ac.th
ajarnelindert@gmail.com
mprima@chula.ac.th
ingo.p@chula.ac.th
pnattama@chula.ac.th
pnattama@gmail.com
darin.p@chula.ac.th
bancha.r@chula.ac.th
brattana.b@gmail.com
jiranthara.s@chula.ac.th
nipaporn.chula@gmail.com
tiranasawasdin@gmail.com
simonjpwright@hotmail.com
englishdepartment@chula.ac.th

Scraping news#


url = 'https://thestandard.co/metaverse-and-investment-opportunities/'
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
d = soup.select('div.entry-content')
len(d)
1
url.split('/')[-2]
'metaverse-and-investment-opportunities'
with open(url.split('/')[-2] + '.txt', mode='w') as f:
  f.write(d[0].text)
main_url = 'https://thestandard.co/category/wealth/wealth-opinion/'
page = requests.get(main_url)
soup = BeautifulSoup(page.content, 'html.parser')
soup.select('h3.news-title a')
[<a href="https://thestandard.co/metaverse-and-investment-opportunities/">
 Metaverse กับความสำคัญในโลกอนาคตและโอกาสการลงทุนในโลกเสมือนจริง </a>,
 <a href="https://thestandard.co/direction-of-thai-economy-after-open-city/">
 ทิศทางเศรษฐกิจไทยหลังการเปิดเมือง </a>,
 <a href="https://thestandard.co/thai-education-crisis/">
 เด็กฉลาด ชาติเจริญ: จะฉลาดอย่างไรในวันที่ต้องเรียนออนไลน์ </a>,
 <a href="https://thestandard.co/esg-investing-responsible-investor/">
 ESG Investing บทบาทของนักลงทุนสไตล์ Responsible Investor </a>,
 <a href="https://thestandard.co/world-oil-price-increase-effect-thailand-ecoomy/">
 ราคาน้ำมันโลกพุ่งสูง เสี่ยงต่อการฟื้นตัวของเศรษฐกิจไทยอย่างไร </a>,
 <a href="https://thestandard.co/cop26-and-investment-opportunities/">
 เจาะลึกการประชุม COP26 และโอกาสการลงทุนจากธีมรักษ์โลกที่มากกว่าแค่พลังงานทดแทน </a>,
 <a href="https://thestandard.co/wgc-and-gold-reserve-in-3q2021/">
 WGC ชี้แบงก์ชาติทั่วโลกเดินหน้าสำรองทองเพิ่มใน 3Q21 ‘ไทย’ ยืนหนึ่งถือทองเพิ่มมากสุดในปีนี้ </a>,
 <a href="https://thestandard.co/adjust-investment-for-better/">
 ปรับตัวพร้อมเปลี่ยนโลกการลงทุนครั้งใหญ่ เพื่อสิ่งที่ดีกว่า </a>,
 <a href="https://thestandard.co/blockchain-platform-war/">
 สงคราม​แพลตฟอร์ม Blockchain </a>,
 <a href="https://thestandard.co/thematic-investor-2021-ending-expectation/">
 Thematic Investor กับความหวังท้ายปี 2021 </a>]
a_tags = soup.select('div.newsbox-archive h3.news-title a')
a_tags
[<a href="https://thestandard.co/metaverse-and-investment-opportunities/">
 Metaverse กับความสำคัญในโลกอนาคตและโอกาสการลงทุนในโลกเสมือนจริง </a>,
 <a href="https://thestandard.co/direction-of-thai-economy-after-open-city/">
 ทิศทางเศรษฐกิจไทยหลังการเปิดเมือง </a>,
 <a href="https://thestandard.co/thai-education-crisis/">
 เด็กฉลาด ชาติเจริญ: จะฉลาดอย่างไรในวันที่ต้องเรียนออนไลน์ </a>,
 <a href="https://thestandard.co/esg-investing-responsible-investor/">
 ESG Investing บทบาทของนักลงทุนสไตล์ Responsible Investor </a>,
 <a href="https://thestandard.co/world-oil-price-increase-effect-thailand-ecoomy/">
 ราคาน้ำมันโลกพุ่งสูง เสี่ยงต่อการฟื้นตัวของเศรษฐกิจไทยอย่างไร </a>,
 <a href="https://thestandard.co/cop26-and-investment-opportunities/">
 เจาะลึกการประชุม COP26 และโอกาสการลงทุนจากธีมรักษ์โลกที่มากกว่าแค่พลังงานทดแทน </a>,
 <a href="https://thestandard.co/wgc-and-gold-reserve-in-3q2021/">
 WGC ชี้แบงก์ชาติทั่วโลกเดินหน้าสำรองทองเพิ่มใน 3Q21 ‘ไทย’ ยืนหนึ่งถือทองเพิ่มมากสุดในปีนี้ </a>,
 <a href="https://thestandard.co/adjust-investment-for-better/">
 ปรับตัวพร้อมเปลี่ยนโลกการลงทุนครั้งใหญ่ เพื่อสิ่งที่ดีกว่า </a>,
 <a href="https://thestandard.co/blockchain-platform-war/">
 สงคราม​แพลตฟอร์ม Blockchain </a>,
 <a href="https://thestandard.co/thematic-investor-2021-ending-expectation/">
 Thematic Investor กับความหวังท้ายปี 2021 </a>]
for a in a_tags:
  print(a.attrs['href'])
https://thestandard.co/metaverse-and-investment-opportunities/
https://thestandard.co/direction-of-thai-economy-after-open-city/
https://thestandard.co/thai-education-crisis/
https://thestandard.co/esg-investing-responsible-investor/
https://thestandard.co/world-oil-price-increase-effect-thailand-ecoomy/
https://thestandard.co/cop26-and-investment-opportunities/
https://thestandard.co/wgc-and-gold-reserve-in-3q2021/
https://thestandard.co/adjust-investment-for-better/
https://thestandard.co/blockchain-platform-war/
https://thestandard.co/thematic-investor-2021-ending-expectation/
def scrape_article(url):
  page = requests.get(url)
  soup = BeautifulSoup(page.content, 'html.parser')
  d_list = soup.select('div.entry-content')
  t = d_list[0].text
  with open(url.split('/')[-2] + '.txt', mode='w') as f:
    f.write(t)

num_pages = 5
for i in range(num_pages+1):
  if i == 0:
    link_page = 'https://thestandard.co/category/wealth/wealth-opinion/'
  else:
    link_page = 'https://thestandard.co/category/wealth/wealth-opinion/page/{}/'.format(i)
  result = requests.get(link_page)
  link_page_soup = BeautifulSoup(result.content, 'html.parser')
  article_a_tags = link_page_soup.select('div.newsbox-archive h3.news-title a')
  for a_tag in article_a_tags:
    scrape_article(a_tag.attrs['href'])
!zip mydata.zip *.txt 
  adding: 4-lessons-evergrande.txt (deflated 77%)
  adding: adjust-investment-for-better.txt (deflated 75%)
  adding: bank-and-regulator.txt (deflated 78%)
  adding: blockchain-platform-war.txt (deflated 73%)
  adding: bot-ltv.txt (deflated 78%)
  adding: cop26-and-investment-opportunities.txt (deflated 75%)
  adding: core-satellite-stock-portfolio.txt (deflated 77%)
  adding: direction-of-thai-economy-after-open-city.txt (deflated 76%)
  adding: educational-institutions-make-a-lot-money-is-good-or-not.txt (deflated 74%)
  adding: energy-crisis-and-stagflation-fear.txt (deflated 79%)
  adding: energy-prices-opening-up-the-country-and-the-volatility-of-the-baht.txt (deflated 79%)
  adding: esg-investing-responsible-investor.txt (deflated 73%)
  adding: evergrande-case.txt (deflated 77%)
  adding: fake-testament-vulnerability-closing-before-blood-inherit.txt (deflated 78%)
  adding: foundations-and-principles-of-economic-reform.txt (deflated 82%)
  adding: gold-movement-with-qe-tapering-in-2013.txt (deflated 77%)
  adding: healthcare-innovation-fund.txt (deflated 75%)
  adding: hyperscale-data-center.txt (deflated 73%)
  adding: if-its-insured-its-good.txt (deflated 76%)
  adding: lockdown-released-and-determine-fate-of-thai-stock-market.txt (deflated 75%)
  adding: margaret-thatcher.txt (deflated 78%)
  adding: ma-trend-in-world-financial-industry.txt (deflated 76%)
  adding: metaverse-and-investment-opportunities.txt (deflated 72%)
  adding: opinion-insurance-meet-pay-finish.txt (deflated 76%)
  adding: prevent-and-cope-with-cyber-threat.txt (deflated 78%)
  adding: public-debt-ceiling-in-us.txt (deflated 74%)
  adding: qe-tapering-to-debt-ceiling-lifting.txt (deflated 78%)
  adding: random-credit-card-numbers.txt (deflated 77%)
  adding: reduce-taxes-to-be-worthwhile.txt (deflated 79%)
  adding: reform-from-motivation.txt (deflated 81%)
  adding: selective-buy.txt (deflated 65%)
  adding: set-fluctuate-to-defensive-group.txt (deflated 74%)
  adding: slowflation-investment.txt (deflated 77%)
  adding: spacs-opportunities-and-risks-of-a-new-way.txt (deflated 78%)
  adding: thai-baht-value-2022-on-4-factors.txt (deflated 81%)
  adding: thai-bank-shares-value-last-compared-to-foreign-countries.txt (deflated 79%)
  adding: thai-education-crisis.txt (deflated 79%)
  adding: the-great-reset-in-business-sector.txt (deflated 76%)
  adding: the-law-of-foreign-ownership-of-land.txt (deflated 79%)
  adding: thematic-investor-2021-ending-expectation.txt (deflated 71%)
  adding: thematic-investor-with-worst-month-of-2021.txt (deflated 71%)
  adding: uk-economy-lesson.txt (deflated 77%)
  adding: wgc-and-gold-reserve-in-3q2021.txt (deflated 74%)
  adding: which-market-to-invest-when-global-monetary-policy-began-to-differ.txt (deflated 76%)
  adding: who-responsible-customers-sucked-in-money-case.txt (deflated 76%)
  adding: why-climate-change-strategy-importance.txt (deflated 73%)
  adding: why-open-the-city-and-the-economy-is-still-broken.txt (deflated 77%)
  adding: world-business-trend-during-coronavirus-from-executive-view.txt (deflated 76%)
  adding: world-oil-price-increase-effect-thailand-ecoomy.txt (deflated 78%)
  adding: year-ending-investment-portfolio.txt (deflated 76%)