Я новичок в Python и Selenium и задаюсь вопросом, как я могу взять группу текста с веб-страницы и ввести ее в массив. В настоящее время у меня есть метод, который вместо использования массива использует строку и нечетко отображает ее.
# returns a list of names in the order it is displayed
def gather_names(self):
fullListNames = ""
hover_names = self.browser.find_elements_by_xpath("//div[contains(@class, 'recent-names')]") #xpath to the names that will need to be hovered over
for names in hover_names:
self.hover_over(names) #hover_over is a method which takes an xpath and will then hover over each of those elements
self.wait_for_element("//div[contains(@class, 'recent-names-info')]", 'names were not found') #Checking to see if it is displayed on the page; otherwise, a 'not found' command will print to console
time.sleep(3) #giving it time to find each element, otherwise it will go too fast and skip over one
listName = names.find_element_by_xpath("//div[contains(@class, 'recent-names-info')]").text #converts to text
fullListNames += listName #currently adding every element to a string
return fullListNames
Результат этого выглядит как
name_on_page1name_on_page2name_on_page3
без пробелов между именами (которые я хотел бы изменить, если не смогу найти способ включить это в массив).
Когда я попытался создать массив fullListNames, у меня возникли проблемы с захватом каждого символа строки, а результат выглядел примерно так:
[u'n', u'a', u'm', u'e', u'_', u'o', u'n']....
Предпочтительно, мне нужен формат
[name1, name2, name3]
Может ли кто-нибудь указать правильный способ справиться с этим?






И fullListNames, и listName - это струны. Строкой fullListNames += listName вы объединяете эти две строки. Затем все имена объединяются в одну длинную строку.
Вам просто нужно инициализировать fullListNames пустым списком: fullListNames = []. Затем добавьте к этому списку listName: fullListNames.append(listName).
You are using string concatnation here ..
fullListNames += listName // thats the problem please refer below code i have replaced the selenium components you can add it depending upon your requirement.
also fullListNames should be an array
fullListNames =[]
def gather_names1():
fullListNames = []
#hover_names = self.browser.find_elements_by_xpath("//div[contains(@class, 'recent-names')]") #xpath to the names that will need to be hovered over
# #for names in hover_names:
# self.hover_over(names) #hover_over is a method which takes an xpath and will then hover over each of those elements
# self.wait_for_element("//div[contains(@class, 'recent-names-info')]", 'names were not found') #Checking to see if it is displayed on the page; otherwise, a 'not found' command will print to console
# time.sleep(3) #giving it time to find each element, otherwise it will go too fast and skip over one
# listName = names.find_element_by_xpath("//div[contains(@class, 'recent-names-info')]").text #converts to text
for i in range(10):
listName = "user"+str(i)
fullListNames.append(listName)#currently adding every element to a string
print fullListNames
return fullListNames
gather_names1()
i got the below output
['user0', 'user1', 'user2', 'user3', 'user4', 'user5', 'user6', 'user7', 'user8', 'user9']