好,所以我有这个数组
import unittest
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
import time
class GoogleEveryFirstLink(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome(executable_path=r'D:\Test automation\chromedriver.exe')
self.driver.get("http://www.google.com")
def test_Hover_Facebook(self):
driver = self.driver
self.assertIn("Google",driver.title)
elem=driver.find_element_by_id("lst-ib")
elem.clear()
elem.send_keys("India")
elem.send_keys(Keys.RETURN)
page_counter=2
links_counter=1
wait = WebDriverWait(driver,20)
wait.until(EC.element_to_be_clickable((By.XPATH,"(//h3[@class='r']/a)[" + str(links_counter) + "]")))
pages=driver.find_elements_by_xpath("//*[@id='nav']/tbody/tr/td/a")
elem1=driver.find_elements_by_xpath("//h3[@class='r']/a")
print len(elem1)
print len(pages)
driver.maximize_window()
for page in pages:
for e in elem1:
my_link = driver.find_element_by_xpath("(//h3[@class='r']/a)[" + str(links_counter) + "]")
print my_link.text
my_link.click()
driver.back()
links_counter+=1
my_page = driver.find_element_by_xpath("//a[text() = '" + str(page_counter) + "']")
my_page.click()
page_counter+=1
def tearDown(self):
self.driver.close()
if __name__=="__main__":
unittest.main()
到目前为止,这对我来说仍然有效,因为我不必在阵列中走低。
"status": "ok",
"totalResults": 20,
"articles": [
{
"source": {
"id": "techcrunch",
"name": "TechCrunch"
},
"author": "Emma Lee",
"title": "The incredible rise of Pinduoduo, China's newest force in e-commerce",
"description": "Editor’s note: This post originally appeared on TechNode, an editorial partner of TechCrunch based in China. From Alibaba to JD, China is not short of e-commerce powerhouses. Although the country’s e-commerce market is highly consolidated, it’s not impossible…",
"url": "https://techcrunch.com/2018/07/26/the-incredible-rise-of-pinduoduo/",
"urlToImage": "https://techcrunch.com/wp-content/uploads/2018/07/Pinduoduo.jpeg?w=750",
"publishedAt": "2018-07-27T03:39:00Z"
},
但是,如果我尝试这样做
echo $queries['status'];
echo '<br />';
echo "Total Results: ". $queries['totalResults'];
它不起作用。
答案 0 :(得分:1)
articles
包含一个对象数组,并且作者在文章array of object
中。如果要找作者,则应在$ queries上应用循环。
foreach ($queries as $query ) {
echo $query['articles']->author;
}
或直接将其获取为:
$queries['articles'][0]->author
答案 1 :(得分:0)
您的原始查询似乎只返回了一篇文章。您最初发布的代码是尝试访问数组顶部的author键,但是author键实际上嵌套在articles数组下。这是我尝试的方法,仅用于检索活动作者:
echo $queries["articles"][0]["author"];
答案 2 :(得分:0)
您正在使用JSON
对象,这首先需要转换为PHP
对象。无法直接访问JSON
对象,因此将您的对象转换为字符串。
$queries = '{
"status": "ok",
..........
}';
$queries = json_decode($queries);
$articles = $queries->articles;
foreach ($articles as $articleKey => $articleVal) {
echo articleVal->author;
}
答案 3 :(得分:-1)
foreach ($queries['articles'] as $article) {
echo $article->author;
}
尝试一下