2017-08-04 36 views
0

我有一個Python代碼,它返回BBC新聞報道的標題和第一段,但目前我必須提供鏈接。代碼如下:Python - 從網址抓取標題,但網址來自用戶輸入

from lxml import html 
import requests 

response = requests.get('http://www.bbc.co.uk/news/business-40660355') 

if (response.status_code == 200): 

    pagehtml = html.fromstring(response.text) 

    news1 = pagehtml.xpath('//h1[@class="story-body__h1"]/text()') 
    news2 = pagehtml.xpath('//p[@class="story-body__introduction"]/text()') 
print("\n".join(news1) + " (BBC News)") 
print("\n".join(news2)) 

但是這段代碼依賴於將URL複製到requests.get('')位。

這是我在將其更改爲允許用戶輸入的嘗試:

from lxml import html 
import requests 

response = input() 

if (response.status_code == 200): 

    pagehtml = html.fromstring(response.text) 

    news1 = pagehtml.xpath('//h1[@class="story-body__h1"]/text()') 
    news2 = pagehtml.xpath('//p[@class="story-body__introduction"]/text()') 
print("\n".join(news1) + " (BBC News)") 
print("\n".join(news2)) 

但不幸的是,已經返回了以下錯誤:

http://www.bbc.co.uk/news/world-europe-40825668 
Traceback (most recent call last): 
    File "myscript2.py", line 5, in <module> 
    response = input() 
    File "<string>", line 1 
    http://www.bbc.co.uk/news/world-europe-40825668 
     ^
SyntaxError: invalid syntax 

我想知道是否有人知道的最好的方法通過獲取輸入來獲取此代碼的工作方式,而不是依靠用戶更改代碼以從URL中獲取信息。

感謝

+0

除非您使用python3,否則您需要'raw_input'。 – jordanm

+0

另外,我想說你想要的東西沿線︰ 'response = requests.get(input())' – tmarice

+0

嗨@jordanm,我使用Python 3.5謝謝 –

回答

0

這裏是你正在尋找的東西:

from lxml import html 
import requests 

url = raw_input('Enter a URL: ') 
response = requests.get(url) 

if (response.status_code == 200): 
    pagehtml = html.fromstring(response.text) 

    news1 = pagehtml.xpath('//h1[@class="story-body__h1"]/text()') 
    news2 = pagehtml.xpath('//p[@class="story-body__introduction"]/text()') 
print("\n".join(news1) + " (BBC News)") 
print("\n".join(news2)) 

爲了把結果放在一個.txt文件,使用以下命令:

with open('fileName.txt', 'a') as output: 
    output.write(news1 + '\n') 
+0

謝謝Anoop - 在玩它,我幾乎準確地降落了你的東西 - 我以前沒有想過要把繩子放在前面,所以我很感激。我贊成你,但是因爲我的代表不到15歲,顯然沒有計算在內! –

+0

當然人!很高興它解決了! –

+0

現在要弄清楚如何將結果打印到一個txt文件中... –

0

我不知道「回答你自己的問題」是很常見的做法,但我已經解決了。我的raw_input使用代替了,換成我的輸入(),但:

my_url = raw_input() 
response = requests.get(my_url) 

不知道是否有人會看到這一點,但希望它幫助!

+0

在這裏您可以自己提出問題,這很好。您甚至可以將其標記爲已接受。 – RedX