LXML No se puede recuperar la página web con un error "Error al cargar el recurso HTTP"
Pregunta
Hola, así que intenté abrir el siguiente enlace en un navegador y funciona pero no en el código.El enlace es en realidad una combinación de un sitio de noticias y luego la extensión del artículo llamado desde otro archivo URL.TXT.Probé el código con un sitio web normal (www.google.com) y funciona perfectamente.
import sys
import MySQLdb
from mechanize import Browser
from bs4 import BeautifulSoup, SoupStrainer
from nltk import word_tokenize
from nltk.tokenize import *
import urllib2
import nltk, re, pprint
import mechanize #html form filling
import lxml.html
with open("url.txt","r") as f:
first_line = f.readline()
#print first_line
url = "http://channelnewsasia.com/&s" + (first_line)
t = lxml.html.parse(url)
print t.find(".//title").text
y este es el error que estoy recibiendo.
y este es el contenido de url.txt
/news/asiapacific/australia-a-send-armed/1284790.html
Solución
Esto se debe a la parte &s
de la URL: definitivamente no es necesario:
url = "http://channelnewsasia.com" + first_line
Además, se deben unir las piezas de URL usando urljoin()
:
from urlparse import urljoin
import lxml.html
BASE_URL = "http://channelnewsasia.com"
with open("url.txt") as f:
first_line = f.readline()
url = urljoin(BASE_URL, first_line)
t = lxml.html.parse(url)
print t.find(".//title").text
Impresiones:
Australia to send armed personnel to MH17 site - Channel NewsAsia
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow