我有一个Python代码,它返回BBC新闻报道的标题和第一段,但目前我必须提供链接。这是代码:
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 :(得分: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')
答案 1 :(得分:0)
我不知道“回答你自己的问题”是否是常见做法,但我已经解决了。我改为使用了raw_input,并使用:
替换了我的input()original points to value 50
shared_original points to value 50
thief points to nullptr
original points to nullptr
shared_original points to nullptr
thief points to value 50
不确定是否有其他人会看到这一点,但希望它有所帮助!