1c94a19 2 years ago
1 contributor
60 lines | 2.69kb
# ~ from userio import *
import userio
import requests
import re
import newsParser
from requests_html import HTML
from requests_html import HTMLSession


def article(url):
  say("Article: "+url)
  session = HTMLSession()
  response = session.get(url,timeout=20)
  pageContent=""
  article_only=""
  with response as r:
    articleStrTitle = r.html.xpath('//meta[@property="og:title"]/@content')[0]
    articleStrDescription = r.html.xpath('//meta[@property="og:description"]/@content')[0]
    articleStrImageUrl = r.html.xpath('//meta[@property="og:image"]/@content')[0]
    articleStrAuthor = r.html.xpath('//div[@class="author_wrapper"]/@content')
    article=r.html.find("main")[0]
    article_only+=article.html
    lenBefore=len(article_only)
    say("LengthBefore: "+str(lenBefore))
    pageContent += "<meta property=\"og:type\" content=\"article\" />\n"
    pageContent += "<meta property=\"og:title\" content=\""+articleStrTitle+"\" />\n"
    pageContent += "<meta property=\"og:description\" content=\""+articleStrDescription+"\" />\n"
    pageContent += "<meta property=\"og:url\" content=\""+url+"\" />\n"
    pageContent += "<meta property=\"og:image\" content=\""+articleStrImageUrl+"\" />\n"
    pageContent += "<meta property=\"og:image:type\" content=\"image/jpeg\" />\n"
    #pageContent += "<meta name=\"author\" content=\""+articleStrAuthor+"\" />\n"

  article_only = re.sub(r"<amp-img", '<img', article_only)
  article_only = re.sub(r"</amp-img>", '', article_only)
  article_only = re.sub(r"<h2", '<h3', article_only)
  article_only = re.sub(r"</h2>", '</h3>', article_only)
  article_only = re.sub(r"<h1", '<h2', article_only)
  article_only = re.sub(r"</h1>", '</h2>', article_only)
  article_only = re.sub(r'<script(.+?)</script>','',article_only,flags=re.M|re.S)
  article_only = re.sub(r'<script(.+?)/>','',article_only)
  #article_only = re.sub(r'','',article_only)
  article_only = re.sub(r"href=\"/",'href="https://xxxxx/',article_only)
  article_only = re.sub(r"src=\"/",'src="https://xxxxx/',article_only)
  article_only = re.sub(r"^$",'',article_only)
  article_only = re.sub(r'^\s*$', '',article_only,flags=re.M|re.S)
  article_only = re.sub(r"><",'>\n<',article_only)

  #pageContent += "\n"+article_only+"\n"
  pageContent += "<article>\n"+article_only+"\n</article>\n"
  lenAfter=len(article_only)
  lenGain=float(10000-int(float(100*lenAfter/lenBefore)*100))/100
  say("LengthAfter : "+str(lenAfter))
  say("Gain        : "+str(lenGain)+"%")
  return pageContent

if __name__ == "__main__":        
  #global server
  url="https://www.nytimes.com/2023/03/05/technology/artificial-intelligence-breast-cancer-detection.html"
  print(url)
  article(url)