我有一個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中獲取信息。
感謝
除非您使用python3,否則您需要'raw_input'。 – jordanm
另外,我想說你想要的東西沿線︰ 'response = requests.get(input())' – tmarice
嗨@jordanm,我使用Python 3.5謝謝 –