2017-08-04 40 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