目前我已经将Selenium连接到python来抓取一个网页.我发现页面实际上是从JSON API中提取数据,只要我登录到页面,我就可以获得JSON响应.
但是,我将这种响应转化为python的方法似乎有点混乱; 我选择包含在<pre>标签中的文本并使用python的json包来解析数据,如下所示:
import json
from selenium import webdriver
url = 'http://jsonplaceholder.typicode.com/posts/1'
driver = webdriver.Chrome()
driver.get(url)
json_text = driver.find_element_by_css_selector('pre').get_attribute('innerText')
json_response = json.loads(json_text)
Run Code Online (Sandbox Code Playgroud)
我需要在<pre>标签中选择的唯一原因是因为当JSON出现在Chrome中时,它的格式如下:
<html>
<head></head>
<body>
<pre style="word-wrap: break-word; white-space: pre-wrap;">{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}</pre>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我需要在selenium中完成此操作的唯一原因是因为我需要登录网站以获得响应.否则我得到401而没有数据.
如果模块只在直接执行脚本时使用,将import语句放在if __name__ == '__main__'节的顶部而不是脚本的顶部是否可以接受?
例子:
def open_as_clean_list(filename):
list = []
with open(filename) as f:
for line in f:
li = line.rstrip()
if not li.startswith("#") and li:
list.append(li)
return list
if __name__ == '__main__':
import random
first = open_as_clean_list("first.txt")
second = open_as_clean_list("second.txt")
print(random.choice(first) + ' ' + random.choice(second))
Run Code Online (Sandbox Code Playgroud)
如您所见,random仅当代码直接运行时才需要。最佳做法是无论如何导入,还是仅在直接执行时才导入?模块实际上是什么有什么不同吗?