Difference between revisions of "Python: Read URL"

From OnnoWiki
Jump to navigation Jump to search
Line 1: Line 1:
 +
pip install urllib
 
  pip install requests
 
  pip install requests
 
  pip install BeautifulSoup4
 
  pip install BeautifulSoup4
Line 14: Line 15:
 
  all_text = ''.join(soup.findAll(text=True))
 
  all_text = ''.join(soup.findAll(text=True))
 
  print(all_text)
 
  print(all_text)
 +
 +
 +
 +
 +
 +
Atau
 +
 +
 +
import urllib
 +
from bs4 import BeautifulSoup
 +
 +
url = "http://news.bbc.co.uk/2/hi/health/2284783.stm"
 +
html = urllib.urlopen(url).read()
 +
soup = BeautifulSoup(html)
 +
 +
# kill all script and style elements
 +
for script in soup(["script", "style"]):
 +
    script.extract()    # rip it out
 +
 +
# get text
 +
text = soup.get_text()
 +
 +
# break into lines and remove leading and trailing space on each
 +
lines = (line.strip() for line in text.splitlines())
 +
# break multi-headlines into a line each
 +
chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
 +
# drop blank lines
 +
text = '\n'.join(chunk for chunk in chunks if chunk)
 +
print(text)
  
  

Revision as of 09:13, 29 April 2019

pip install urllib
pip install requests
pip install BeautifulSoup4

Script

import requests
from BeautifulSoup import BeautifulSoup

link = "http://www.somesite.com/details.pl?urn=2344"
f = requests.get(link)
print(f.text)
soup = BeautifulSoup(f)
all_text = .join(soup.findAll(text=True))
print(all_text)



Atau


import urllib
from bs4 import BeautifulSoup

url = "http://news.bbc.co.uk/2/hi/health/2284783.stm"
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)

# kill all script and style elements
for script in soup(["script", "style"]):
    script.extract()    # rip it out

# get text
text = soup.get_text()

# break into lines and remove leading and trailing space on each
lines = (line.strip() for line in text.splitlines())
# break multi-headlines into a line each
chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
# drop blank lines
text = '\n'.join(chunk for chunk in chunks if chunk)
print(text)


Pranala Menarik