LXML não consegue recuperar página da web com erro “falha ao carregar recurso HTTP”

StackOverflow https://stackoverflow.com//questions/25007501

  •  20-12-2019
  •  | 
  •  

Pergunta

Olá, tentei abrir o link abaixo em um navegador e funciona, mas não no código.O link é na verdade uma combinação de um site de notícias e a extensão do artigo chamada de outro arquivo url.txt.Tentei o código com um site normal (www.google.com) e funcionou perfeitamente.

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

E este é o erro que estou recebendo.

enter image description here

E este é o conteúdo de url.txt

/news/asiapacific/australia-to-send-armed/1284790.html

Foi útil?

Solução

Isto é por causa do &s parte do URL - definitivamente não é necessário:

url = "http://channelnewsasia.com" + first_line

Além disso, é melhor unir as partes do 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

impressões:

Australia to send armed personnel to MH17 site - Channel NewsAsia
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top