The data parased from the website ended up with being an empty data (bs4, python, lxml) - beautifulsoup

Hello Stackoverflow folks,
I have had a very hardtime with parsing information from a website
using Beautifulsoup and lxml.
I tried to bring the address data from "https://www1.nyc.gov/events/events-filter.html#page-1" website.
As far as I googled,
it says I need to
1. find the specific class for the information through "inspection" of the webpage.
2. need to write a code like g_data = soup.find_all("div", {"class": "event-data-detail"})
So I wrote my code as below.
import requests
from bs4 import BeautifulSoup
url = "https://www1.nyc.gov/events/events-filter.html#page-1"
r=requests.get("https://www1.nyc.gov/events/events-filter.html#page-1")
soup = BeautifulSoup(r.content)
links = soup.find_all("a")
g_data = soup.find_all("div", {"class": "event-data-detail"})
print(g_data)
and it shows the error message
Warning (from warnings module): File
"C:/Users/jotna/Desktop/Portfolio/1.py", line 7
soup = BeautifulSoup(r.content) UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for
this system ("lxml"). This usually isn't a problem, but if you run
this code on another system, or in a different virtual environment, it
may use a different parser and behave differently.
The code that caused this warning is on line 7 of the file
C:/Users/jotna/Desktop/Portfolio/1.py. To get rid of this warning,
pass the additional argument 'features="lxml"' to the BeautifulSoup
constructor.
So I fixed the code as below. (Cause a posting in stackoverflow suggested to add lxml code at the end)
import lxml
import requests
from bs4 import BeautifulSoup
url = "https://www1.nyc.gov/events/events-filter.html#page-1"
r=requests.get("https://www1.nyc.gov/events/events-filter.html#page-1")
soup = BeautifulSoup(r.content)
links = soup.find_all("a")
for link in links:
if "http" in link.get("href"):
print ("<a href='%s'>%s</a>" %(link.get("href"), link.text))
g_data = soup.find_all("div", {"span class": "address"})
print(g_data)
However it only shows empty bracket
[]
How can actually bring the address data from the website?
For your information, I uploaded the screen shot of the webpage source as well.
enter image description here

Use their json api instead of bs4, see the code below.
import requests
count = 0
for i in range(185):
count+=1
link = 'https://www1.nyc.gov/calendar/api/json/search.htm?&sort=DATE&pageNumber='+str(count)
req = requests.get(link)
for i in req.json()['items']:
address = (i['address'])
print 'Address:', address
Output
Address: Mulberry Street, Little Italy, New York
Address: Various locations Citywide
Address: SECOND AVENUE between EAST 32 STREET and EAST 33 STREET Manhattan
Address: FIRST AVENUE between EAST 92 STREET and EAST 93 STREET Manhattan
Address: CARROLL STREET between SMITH STREET and COURT STREET Brooklyn
Address: BROADWAY between WEST 114 STREET and WEST 116 STREET Manhattan
Address: CORTELYOU ROAD between RUGBY ROAD and ARGYLE ROAD Brooklyn
Address: QUEENS BOULEVARD between 70 AVENUE and 69 ROAD Queens
Address: 79 STREET between NORTHERN BOULEVARD and 34 AVENUE Queens
Address: PRINCE STREET between MOTT STREET and MULBERRY STREET Manhattan
Address: BUSHWICK AVENUE between NOLL STREET and ARION PLACE Brooklyn
Address: Alley Pond Park Adventure Center
Address: Atlantic Avenue between 4th Avenue and Hicks Street
Address: Alexander von Humboldt statue - Central Park West and 77th Street
Address: SEVENTH AVENUE between WEST 110 STREET and WEST 111 STREET Manhattan
Address: Wave Hill House - West 249th Street and Independence Avenue
Address: Broadway between Liberty Street and Rector Street
Address: Anibal Aviles Playground
Address: Myrtle Avenue between Fresh Pond Road and Wyckoff Avenue

Related

Problem with getting the locator of a dropdown in Selenium

Please take a look at the page # https://www.kayak.co.in/stays. When I type a location say New Delhi in the Location textbox a dropdown appears indicating the list of options to be selected. However when I try to identify that element using the Dev Tools by clicking it, it disappears and a I am not able to obtain the locator. I tried passing the locator along with Key Action Enter: i.e. SendKeys(locator + Keys.Enter) as per the UI behavior but even it fails to work which is blocking my script. Please let me know how to proceed.
As mentioned I am not able to get the dropdown locator and Keys.Enter doesn't even work
Here's a full SeleniumBase script (https://github.com/seleniumbase/SeleniumBase) that will do all that for you. pip install seleniumbase, and then run the script with python or pytest. The sleeps are only there so that you can see what's happening. Otherwise it runs very fast!
from seleniumbase import BaseCase
if __name__ == "__main__":
from pytest import main
main([__file__])
class KayakTest(BaseCase):
def test_kayak_search(self):
self.open("https://www.kayak.co.in/stays")
self.type(
'input[placeholder*="Enter a city"]',
"New Delhi, National Capital Territory of India"
)
self.sleep(1)
self.add_text('input[placeholder*="Enter a city"]', "\n")
self.sleep(1)
self.click("div.ATGJ-monthWrapper div:nth-of-type(2) div:nth-of-type(2) div:nth-of-type(23)")
self.sleep(1)
self.click("div.ATGJ-monthWrapper div:nth-of-type(2) div:nth-of-type(2) div:nth-of-type(27)")
self.sleep(1)
self.click("svg.c8LPF-icon")
self.sleep(5)
This is the full XPath. Feel free to remove useless parts.
//body[#id='k4-r'][#class='keel kl kl-override HotelsSearch react react-st wide a11y-focus-outlines wide-fd en_IN horizon'][#style='display: block;']/div[#id='RaKq'][#class='Common-Page-StandardPage Base-Search-LandingPage Base-Search-SearchPage Hotels-Search-HotelSearchPage cur_inr vm-fd dual-view']/div[#id='e6vK'][#class='Common-Layout-StandardBody withFooter']/main[#id='e6vK-pageContent'][#class='pageContent withDrawer moved wide ']/div[#id='RaKq-fd'][#class='SearchPage__FrontDoor']/div[#id='dbfN'][#class='Base-Frontdoor-FrontDoor Hotels-Frontdoor-HotelFrontDoor']/div[#id='VQMg'][#class='Common-Frontdoor-HarmonizedFrontDoorContent']/div[#class='coverPhotoContainer splash'][#data-search-form-container]/div[#id='x0Lx'][#class='_kkL _jcQ _ia2']/div[#id='dbfN-primary'][#class='primary-content']/section/div[#class='keel-container s-t-bp']/div[#class='form-section'][#id='main-search-form']/div[#class='form-container']/div[#id='c2Y_4'][#class='Ui-Searchforms-Hotels-Components-HotelSearchForm-container ']/div[#class='HPw7 HPw7-pres-default HPw7-pres-responsive HPw7-pres-dark HPw7-pres-rooms-guests HPw7-pres-wide-dates']/div[#class='HPw7-form-fields-and-submit']/div[#class='HPw7-form-fields']/div[#class='HPw7-destination']/div[#class='BCcW']/div[#class='k_my k_my-mod-theme-mcfly-search k_my-mod-radius-base k_my-mod-size-large k_my-mod-font-size-base k_my-mod-spacing-default k_my-mod-text-overflow-ellipsis k_my-mod-state-default']/input[#type='text'][#value][#class='k_my-input'][#tabindex='0'][#placeholder='Enter a city, hotel, airport, address or landmark'][#aria-autocomplete='list'][#aria-haspopup='listbox']
Generated by https://github.com/sputnick-dev/retrieveCssOrXpathSelectorFromTextOrNode
Simplified:
//input[#type='text'][#value][#placeholder='Enter a city, hotel, airport, address or landmark'][#aria-haspopup='listbox']
Or after typed new delhi:
//input[#type='text'][#value='Near Indira Gandhi Airport New Delhi India, New Delhi, National Capital Territory of India, India'][#class='k_my-input'][#tabindex='0'][#placeholder='Enter a city, hotel, airport, address or landmark'][#aria-autocomplete='list'][#aria-haspopup='listbox'][#aria-activedescendant='1070140428_hotel_Near Indira Gandhi Airport New Delhi India, New Delhi, National Capital Territory of India, India']

Scraping contents of news articles

I was able to scrape the title, date, links, and content of news on these links: https://www.news24.com/news24/southafrica/crime-and-courts and https://www.news24.com/news24/southafrica/education. The output is saved in an excel file. However, I noticed that not all the contents inside the articles were scrapped. I have tried different methods on my "Getting content section of my code" Any help with this will be appreciate. Below is my code:
import sys, time
from bs4 import BeautifulSoup
import requests
import pandas as pd
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from datetime import timedelta
art_title = [] # to store the titles of all news article
art_date = [] # to store the dates of all news article
art_link = [] # to store the links of all news article
pagesToGet = ['southafrica/crime-and-courts', 'southafrica/education']
for i in range(0, len(pagesToGet)):
print('processing page : \n')
url = 'https://www.news24.com/news24/'+str(pagesToGet[i])
print(url)
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.maximize_window()
try:
driver.get("https://www.news24.com/news24/" +str(pagesToGet[i]))
except Exception as e:
error_type, error_obj, error_info = sys.exc_info()
print('ERROR FOR LINK:', url)
print(error_type, 'Line:', error_info.tb_lineno)
continue
time.sleep(3)
scroll_pause_time = 1
screen_height = driver.execute_script("return window.screen.height;")
i = 1
while True:
driver.execute_script("window.scrollTo(0, {screen_height}{i});".format(screen_height=screen_height, i=i))
i += 1
time.sleep(scroll_pause_time)
scroll_height = driver.execute_script("return document.body.scrollHeight;")
if (screen_height) * i > scroll_height:
break
soup = BeautifulSoup(driver.page_source, 'html.parser')
news = soup.find_all('article', attrs={'class': 'article-item'})
print(len(news))
# Getting titles, dates, and links
for j in news:
titles = j.select_one('.article-item__title span')
title = titles.text.strip()
dates = j.find('p', attrs={'class': 'article-item__date'})
date = dates.text.strip()
address = j.find('a').get('href')
news_link = 'https://www.news24.com' + address
art_title.append(title)
art_date.append(date)
art_link.append(news_link)
df = pd.DataFrame({'Article_Title': art_title, 'Date': art_date, 'Source': art_link})
# Getting Content Section
news_articles = [] # to store the content of each news artcle
news_count = 0
for link in df['Source']:
print('\n')
start_time = time.monotonic()
print('Article No. ', news_count)
print('Link: ', link)
# Countermeasure for broken links
try:
if requests.get(link):
news_response = requests.get(link)
else:
print("")
except requests.exceptions.ConnectionError:
news_response = 'N/A'
# Auto sleep trigger after saving every 300 articles
sleep_time = ['100', '200', '300', '400', '500']
if news_count in sleep_time:
time.sleep(12)
else:
""
try:
if news_response.text:
news_data = news_response.text
else:
print('')
except AttributeError:
news_data = 'N/A'
news_soup = BeautifulSoup(news_data, 'html.parser')
try:
if news_soup.find('div', {'class': 'article__body'}):
art_cont = news_soup.find('div','article__body')
art = []
article_text = [i.text.strip().replace("\xa0", " ") for i in art_cont.findAll('p')]
art.append(article_text)
else:
print('')
except AttributeError:
article = 'N/A'
print('\n')
news_count += 1
news_articles.append(art)
end_time = time.monotonic()
print(timedelta(seconds=end_time - start_time))
print('\n')
# Create a column to add all the scraped text
df['News'] = news_articles
df.drop_duplicates(subset ="Source", keep = False, inplace = True)
# Dont store links
df.drop(columns=['Source'], axis=1, inplace=True)
df.to_excel('SA_news24_3.xlsx')
driver.quit()
I tried the following code in the Getting Content Section as well. However, it produced the same output.
article_text = [i.get_text(strip=True).replace("\xa0", " ") for i in art_cont.findAll('p')]
The site has various types of URLs so your code was omitting them since they found it malformed or some had to be subscribed to read.For the ones that has to be subscribed to read i have added "Login to read" followers by the link in articles . I ran this code till article number 670 and it didn't give any error. I had to change it from .xlsx to .csv since it was giving an error of openpyxl in python 3.11.0.
Full Code
import time
import sys
from datetime import timedelta
import pandas as pd
from bs4 import BeautifulSoup
import requests
import json
art_title = [] # to store the titles of all news article
art_date = [] # to store the dates of all news article
art_link = [] # to store the links of all news article
pagesToGet = ['southafrica/crime-and-courts',
'southafrica/education', 'places/gauteng']
for i in range(0, len(pagesToGet)):
print('processing page : \n')
if "places" in pagesToGet[I]:
url = f"https://news24.com/api/article/loadmore/tag?tagType=places&tag={pagesToGet[i].split('/')[1]}&pagenumber=1&pagesize=100&ishomepage=false&ismobile=false"
else:
url = f"https://news24.com/api/article/loadmore/news24/{pagesToGet[i]}?pagenumber=1&pagesize=1200&ishomepage=false&ismobile=false"
print(url)
r = requests.get(url)
soup = BeautifulSoup(r.json()["htmlContent"], 'html.parser')
news = soup.find_all('article', attrs={'class': 'article-item'})
print(len(news))
# Getting titles, dates, and links
for j in news:
titles = j.select_one('.article-item__title span')
title = titles.text.strip()
dates = j.find('p', attrs={'class': 'article-item__date'})
date = dates.text.strip()
address = j.find('a').get('href')
# Countermeasure for links with full url
if "https://" in address:
news_link = address
else:
news_link = 'https://www.news24.com' + address
art_title.append(title)
art_date.append(date)
art_link.append(news_link)
df = pd.DataFrame({'Article_Title': art_title,
'Date': art_date, 'Source': art_link})
# Getting Content Section
news_articles = [] # to store the content of each news artcle
news_count = 0
for link in df['Source']:
start_time = time.monotonic()
print('Article No. ', news_count)
print('Link: ', link)
news_response = requests.get(link)
news_data = news_response.content
news_soup = BeautifulSoup(news_data, 'html.parser')
art_cont = news_soup.find('div', 'article__body')
# Countermeasure for links with subscribe form
try:
try:
article = art_cont.text.split("Newsletter")[
0]+art_cont.text.split("Sign up")[1]
except:
article = art_cont.text
article = " ".join((article).strip().split())
except:
article = f"Login to read {link}"
news_count += 1
news_articles.append(article)
end_time = time.monotonic()
print(timedelta(seconds=end_time - start_time))
print('\n')
# Create a column to add all the scraped text
df['News'] = news_articles
df.drop_duplicates(subset="Source", keep=False, inplace=True)
# Dont store links
df.drop(columns=['Source'], axis=1, inplace=True)
df.to_csv('SA_news24_3.csv')
Output
,Article_Title,Date,News
0,Pastor gets double life sentence plus two 15-year terms for rape and murder of women,2h ago,"A pastor has been sentenced to two life sentences and two 15-year jail terms for rape and murder His modus operandi was to take the women to secluded areas before raping them and tying them to trees.One woman managed to escape after she was raped but the bodies of two others were found tied to the trees.The North West High Court has sentenced a 50-year-old pastor to two life terms behind bars and two 15-year jail terms for rape and murder.Lucas Chauke, 50, was sentenced on Monday for the crimes, which were committed in 2017 and 2018 in Temba in the North West.According to North West National Prosecuting Authority spokesperson Henry Mamothame, Chauke's first victim was a 53-year-old woman.He said Chauke pretended that he would assist the woman with her spirituality and took her to a secluded place near to a dam.""Upon arrival, he repeatedly raped her and subsequently tied her to a tree before fleeing the scene,"" Mamothame said. The woman managed to untie herself and ran to seek help. She reported the incident to the police, who then started searching for Chauke.READ | Kidnappings doubled nationally: over 4 000 cases reported to police from July to SeptemberOn 10 May the following year, Chauke pounced on his second victim - a 55-year-old woman.He took her to the same secluded area next to the dam, raped her and tied her to a tree before fleeing. This time his victim was unable to free herself.Her decomposed body was later found, still tied to the tree, Mamothame said. His third victim was targeted months later, on 3 August, in the same area. According to Mamothame, Chauke attempted to rape her but failed.""He then tied her to a tree and left her to die,"" he said. Chauke was charged in connection with her murder.He was linked to the crimes via DNA.READ | 'These are not pets': Man gives away his two pit bulls after news of child mauled to deathIn aggravation of his sentence, State advocate Benny Kalakgosi urged the court not to deviate from the prescribed minimum sentences, saying that the offences Chauke had committed were serious.""He further argued that Chauke took advantage of unsuspecting women, who trusted him as a pastor but instead, [he] took advantage of their vulnerability,"" Mamothame said. Judge Frances Snyman agreed with the State and described Chauke's actions as horrific.The judge also alluded to the position of trust that he abused, Mamothame said.Chauke was sentenced to life for the rape of the first victim, 15 years for the rape of the second victim and life for her murder, as well as 15 years for her murder. He was also declared unfit to possess a firearm."
1,'I am innocent': Alleged July unrest instigator Ngizwe Mchunu pleads not guilty,4h ago,"Former Ukhozi FM DJ Ngizwe Mchunu has denied inciting the July 2022 unrest.Mchunu pleaded not guilty to charges that stem from the incitement allegations.He also claimed he had permission to travel to Gauteng for work during the Covid-19 lockdown.""They are lying. I know nothing about those charges,"" alleged July unrest instigator, former Ukhozi FM DJ Ngizwe Brian Mchunu, told the Randburg Magistrate's Court when his trial started on Tuesday.Mchunu pleaded not guilty to the charges against him, which stems from allegations that he incited public violence, leading to the destruction of property, and convened a gathering in contravening of Covid-19 lockdown regulations after the detention of former president Jacob Zuma in July last year.In his plea statement, Mchunu said all charges were explained to him.""I am a radio and television personality. I'm also a poet and cultural activist. In 2020, I established my online radio.READ | July unrest instigators could face terrorism-related charges""On 11 July 2021, I sent invitations to journalists to discuss the then-current affairs. At the time, it was during the arrest of Zuma.""I held a media briefing at a hotel in Bryanston to show concerns over Zuma's arrest. Zuma is my neighbour [in Nkandla]. In my African culture, I regard him as my father.""Mchunu continued that he was not unhappy about Zuma's arrest but added: ""I didn't condone any violence. I pleaded with fellow Africans to stop destroying infrastructure. I didn't incite any violence.I said to them, 'My brothers and sisters, I'm begging you as we are destroying our country.'""He added:They are lying. I know nothing about those charges. I am innocent. He also claimed that he had permission to travel to Gauteng for work during the lockdown.The hearing continues."
2,Jukskei River baptism drownings: Pastor of informal 'church' goes to ground,5h ago,"A pastor of the church where congregants drowned during a baptism ceremony has gone to ground.Johannesburg Emergency Medical Services said his identity was not known.So far, 14 bodies have been retrieved from the river.According to Johannesburg Emergency Medical Services (EMS), 13 of the 14 bodies retrieved from the Jukskei River have been positively identified.The bodies are of congregants who were swept away during a baptism ceremony on Saturday evening in Alexandra.The search for the other missing bodies continues.Reports are that the pastor of the church survived the flash flood after congregants rescued him.READ | Jukskei River baptism: Families gather at mortuary to identify loved onesEMS spokesperson Robert Mulaudzi said they had been in contact with the pastor since the day of the tragedy, but that they had since lost contact with him.It is alleged that the pastor was not running a formal church, but rather used the Jukskei River as a place to perform rituals for people who came to him for consultations. At this stage, his identity is not known, and because his was not a formal church, Mulaudzi could not confirm the number of people who could have been attending the ceremony.Speaking to the media outside the Sandton fire station on Tuesday morning, a member of the rescue team, Xolile Khumalo, said: Thirteen out of the 14 bodies retrieved have been identified, and the one has not been identified yet.She said their team would continue with the search. ""Three families have since come forward to confirm missing persons, and while we cannot be certain that the exact number of bodies missing is three, we will continue with our search."""
3,Six-month-old infant ‘abducted’ in Somerset West CBD,9h ago,"Authorities are on high alert after a baby was allegedly abducted in Somerset West on Monday.The alleged incident occurred around lunchtime, but was only reported to Somerset West police around 22:00. According to Sergeant Suzan Jantjies, spokesperson for Somerset West police, the six-month-old baby boy was taken around 13:00. It is believed the infant’s mother, a 22-year-old from Nomzamo, entrusted a fellow community member and mother with the care of her child before leaving for work on Monday morning. However, when she returned home from work, she was informed that the child was taken. Police were apparently informed that the carer, the infant and her nine-year-old child had travelled to Somerset West CBD to attend to Sassa matters. She allegedly stopped by a liquor store in Victoria Street and asked an unknown woman to keep the baby and watch over her child. After purchasing what was needed and exiting the store, she realised the woman and the children were missing. A case of abduction was opened and is being investigated by the police’s Family Violence, Child Protection and Sexual Offences (FCS) unit. Police obtained security footage which shows the alleged abductor getting into a taxi and making off with the children. The older child was apparently dropped off close to her home and safely returned. However, the baby has still not been found. According to a spokesperson, FCS police members prioritised investigations immediately after the case was reported late last night and descended on the local township, where they made contact with the visibly “traumatised” parent and obtained statements until the early hours of Tuesday morning – all in hopes of locating the child and the alleged suspect.Authorities are searching for what is believed to be a foreign national woman with braids, speaking isiZulu.Anyone with information which could aid the investigation and search, is urged to call Captain Trevor Nash of FCS on 082 301 8910."
4,Have you herd: Dubai businessman didn't know Ramaphosa owned Phala Phala buffalo he bought - report,8h ago,"A Dubai businessman who bought buffaloes at Phala Phala farm reportedly claims he did not know the deal was with President Cyril Ramaphosa.Hazim Mustafa also claimed he was expecting to be refunded for the livestock after the animals were not delivered.He reportedly brought the cash into the country via OR Tambo International Airport, and claims he declared it.A Dubai businessman who reportedly bought 20 buffaloes from President Cyril Ramaphosa's Phala Phala farm claims that he didn't know the deal with was with the president, according to a report.Sky News reported that Hazim Mustafa, who reportedly paid $580 000 (R10 million) in cash for the 20 buffaloes from Ramaphosa's farm in December 2019, said initially he didn't know who the animals belonged to.A panel headed by former chief justice Sandile Ngcobo released a report last week after conducting a probe into allegations of a cover-up of a theft at the farm in February 2020.READ | Ramaphosa wins crucial NEC debate as parliamentary vote on Phala Phala report delayed by a weekThe panel found that there was a case for Ramaphosa to answer and that he may have violated the law and involved himself in a conflict between his official duties and his private business.In a statement to the panel, Mustafa was identified as the source of the more than $500 000 (R9 million) that was stolen from the farm. Among the evidence was a receipt for $580 000 that a Phala Phala employee had written to ""Mr Hazim"".According to Sky News, Mustafa said he celebrated Christmas and his wife's birthday in Limpopo in 2019, and that he dealt with a broker when he bought the animals.He reportedly said the animals were to be prepared for export, but they were never delivered due to the Covid-19 lockdown. He understood he would be refunded after the delays.He also reportedly brought the cash into the country through OR Tambo International Airport and said he declared it. Mustafa also told Sky News that the amount was ""nothing for a businessman like [him]"".READ | Here's the Sudanese millionaire - and his Gucci wife - who bought Ramaphosa's buffaloThe businessman is the owner Sudanese football club Al Merrikh SC. He is married to Bianca O'Donoghue, who hails from KwaZulu-Natal. O'Donoghue regularly takes to social media to post snaps of a life of wealth – including several pictures in designer labels and next to a purple Rolls Royce Cullinan, a luxury SUV worth approximately R5.5 million.Sudanese businessman Hazim Mustafa with his South African-born wife, Bianca O'Donoghue.Facebook PHOTO: Bianca O'Donoghue/Facebook News24 previously reported that he also had ties to former Sudanese president, Omar al-Bashir.There have been calls for Ramaphosa to step down following the saga. A motion of no confidence is expected to be submitted in Parliament.He denied any wrongdoing and said the ANC's national executive committee (NEC) would decide his fate.Do you have a tipoff or any information that could help shape this story? Email tips#24.com"
5,Hefty prison sentence for man who killed stranded KZN cop while pretending to offer help,9h ago,"Two men have been sentenced – one for the murder of a KwaZulu-Natal police officer, and the other for an attempt to rob the officer.Sergeant Mzamiseni Mbele was murdered in Weenen in April last year.He was attacked and robbed when his car broke down on the highway while he was on his way home.A man who murdered a KwaZulu-Natal police officer, after pretending that he wanted to help him with his broken-down car, has been jailed.A second man, who was only convicted of an attempt to rob the officer, has also been sentenced to imprisonment.On Friday, the KwaZulu-Natal High Court in Madadeni sentenced Sboniso Linda, 36, to an effective 25 years' imprisonment, and Nkanyiso Mungwe, 25, to five years' imprisonment.READ | Alleged house robber shot after attack at off-duty cop's homeAccording to Hawks spokesperson, Captain Simphiwe Mhlongo, 39-year-old Sergeant Mzamiseni Mbele, who was stationed at the Msinga police station, was on his way home in April last year when his car broke down on the R74 highway in Weenen.Mbele let his wife know that the car had broken down. While stationary on the road, Linda and Mungwe approached him and offered to help.Mhlongo said: All of a sudden, [they] severely assaulted Mbele. They robbed him of his belongings and fled the scene. A farm worker found Mbele's body the next dayA case of murder was reported at the Weenen police station and the Hawks took over the investigation.The men were arrested.""Their bail [application] was successfully opposed and they appeared in court several times until they were found guilty,"" Mhlongo added.How safe is your neighbourhood? Find out by using News24's CrimeCheckLinda was sentenced to 20 years' imprisonment for murder and 10 years' imprisonment for robbery with aggravating circumstances. Half of the robbery sentence has to be served concurrently, leaving Linda with an effective sentence of 25 years.Mungwe was sentenced to five years' imprisonment for attempted robbery with aggravating circumstances."

Google maps geocoding API address correction hierarchy

I'm trying to understand in what order and what precedence the geocoding API takes when processing the pieces of the address that was passed to it.
I have this example of why I'm asking the question. The correct address is:
2608 N Ocean Bv
Myrtle Beach, SC 29577
Running that into the API, absolutely no problems:
http://maps.googleapis.com/maps/api/geocode/json?address=2608+n+ocean+bv+myrtle+beach+sc+29577&sensor=false
However, take this typoed version of the address:
2608 N Ocean Bv
Mrytle Beach, NC 29577
The city is spelled wrong, and it has the wrong state. Street number, name and zip code are correct. Mrytle Beach does not exist anywhere, and not in NC.
http://maps.googleapis.com/maps/api/geocode/json?address=2608+n+ocean+bv+mrytle+beach+nc+29577&sensor=false
Google comes back with:
2608 N Ocean Bv
North Myrtle Beach, SC 29582
Now, that is a valid address. But why did Google decide that was the address I was looking for?
If you remove the incorrect state, and don't replace it with anything:
http://maps.googleapis.com/maps/api/geocode/json?address=2608+n+ocean+bv+mrytle+beach+29577&sensor=false
Google returns a corrected version of the correct address. So it seems that state trumps zip code - however, North Myrtle Beach does not exist in NC.
I'm thinking that omitting city and state eliminates most of this issue - but I'd like to understand why - if possible. Thanks.
Edit:
After some further playing around - it seems that Google looks for a city match as highest priority, then state - ignore all else. In this case:
Can't find a city called "Mrytle Beach" anywhere in the world.
Let's start in NC then and find the closest match to the street address if there is one.
Ah, here is the closest one to NC - in North Myrtle Beach.
If you change the state in my example above from NC to FL, the more southern Myrtle Beach match is closer to Florida than the more northern North Myrtle Beach address, and that is what Google returns.
I'm trying to understand the reasoning behind this. It seems that this sort of logic would be near last resort - or at least after making use of the zip code passed - which it appears it doesn't use at all.

How to get a brief description about a topic from wiki api?

I need to display a brief description about some topic. Like, when we search "India" on Google, it will show a brief description about India on the right side of the page, but that content is not an actual paragraph from wikipedia. does we get this content from wiki api?
https://www.mediawiki.org/wiki/Extension:TextExtracts#API, for example:
https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exintro=1&explaintext=1&titles=India&continue=&format=json&formatversion=2 outputs
{
"batchcomplete": true,
"query": {
"pages": [
{
"pageid": 14533,
"ns": 0,
"title": "India",
"extract": "India (/ˈɪndiə/), officially the Republic of India (Bhārat Gaṇarājya), is a country in South Asia. It is the seventh-largest country by area, the second-most populous country with over 1.2 billion people, and the most populous democracy in the world. Bounded by the Indian Ocean on the south, the Arabian Sea on the south-west, and the Bay of Bengal on the south-east, it shares land borders with Pakistan to the west; China, Nepal, and Bhutan to the north-east; and Burma (Myanmar) and Bangladesh to the east. In the Indian Ocean, India is in the vicinity of Sri Lanka and the Maldives; in addition, India's Andaman and Nicobar Islands share a maritime border with Thailand and Indonesia.\nHome to the ancient Indus Valley Civilisation and a region of historic trade routes and vast empires, the Indian subcontinent was identified with its commercial and cultural wealth for much of its long history. Four religions—Hinduism, Buddhism, Jainism, and Sikhism—originated here, whereas Zoroastrianism and the Abrahamic religions of Judaism, Christianity, and Islam arrived in the 1st millennium CE and also helped shape the region's diverse culture. Gradually annexed by and brought under the administration of the British East India Company from the early 18th century and administered directly by the United Kingdom after the Indian Rebellion of 1857, India became an independent nation in 1947 after a struggle for independence that was marked by non-violent resistance led by Mahatma Gandhi.\nThe Indian economy is the world's seventh-largest by nominal GDP and third-largest by purchasing power parity (PPP). Following market-based economic reforms in 1991, India became one of the fastest-growing major economies; it is considered a newly industrialised country. However, it continues to face the challenges of poverty, corruption, malnutrition, inadequate public healthcare, and terrorism. A nuclear weapons state and a regional power, it has the third-largest standing army in the world and ranks ninth in military expenditure among nations. India is a federal constitutional republic governed under a parliamentary system consisting of 29 states and 7 union territories. India is a pluralistic, multilingual, and a multi-ethnic society. It is also home to a diversity of wildlife in a variety of protected habitats."
}
]
}
}

Selecting only a single row per id

I'd like to get back only one row per ID, even if there are multiple rows associated with an ID.
The scenario is that the data reflects a site selling land / properties, and that for each listing, there may be multiple images associated with each ID. I need only one.
Thank You.
As requested, sample data:
RowNumber ID UserID CountryID tbl_detailsID Name Description Price AddressLine1 AddressLine2 City State Zip AddressGPS Space Amenities Policies URL DateEntered DateExpires NumViews IsCompanyProperty EnforceMinStay IsOtherSite rate_Avg isFeatured DayPrice ImageURL Name check_in check_out currency bathroom_count pet unit_size elder handicap occupancy bedroom_count LinkURL smoking unit_size_Units property_Type children Minimum_stay Minimum_stay_Unit CountryName
2 247586 1 1 161398 Beautiful Oceanfront Home in Cambria California Located on the Central Coast of California 10 minutes from Hearst Castle.
Phone 1: Toll Free (800) 240-2277
Phone 2: (805) 927-0306 (California, USA)
direct email contact: debbie (#) maisonsdecambria.com
Leopold Cove" is a beautiful Oceanfront Home located on the Central Coast of California. It has fabulous ocean views and access to the water from a private stairway. The living area has large plate glass windows that feature 180 degree views of the Pacific Ocean. A comfortable platform style bed & a warm, cozy fireplace are also located in the living area so you can relax for hours, or even days, enjoying the beauty that surrounds you. There is a full kitchen & a separate bedroom with 2 twin beds. The property also has a picnic area & places to sit, perhaps with a good book & a glass of wine while you watch the sunset. If you are a nature lover, you will enjoy the otters, seals & birdlife that we are privileged to have so close to us. During the gray whale migration times, this is a p 2183 Sherwood Drive Cambria California 93428 35.544712|-121.095444 http://www.flipkey.com/cambria-vacation-rentals/p202618/ 2012-10-01 10:52:00 2012-10-15 10:52:00 0 0 0 703 5.0 0 NULL http://images1.flipkey.com/img/photos/302459/243298/large_302459-243298-007-1346943508.jpg Beautiful Oceanfront Home in Cambria California USD 1 Ask 0 Ask Ask 4 1 http://www.flipkey.com/cambria-vacation-rentals/p202618/ Ask House Ask 0 NULL United States
3 247586 1 1 161398 Beautiful Oceanfront Home in Cambria California Located on the Central Coast of California 10 minutes from Hearst Castle.
Phone 1: Toll Free (800) 240-2277
Phone 2: (805) 927-0306 (California, USA)
direct email contact: debbie (#) maisonsdecambria.com
Leopold Cove" is a beautiful Oceanfront Home located on the Central Coast of California. It has fabulous ocean views and access to the water from a private stairway. The living area has large plate glass windows that feature 180 degree views of the Pacific Ocean. A comfortable platform style bed & a warm, cozy fireplace are also located in the living area so you can relax for hours, or even days, enjoying the beauty that surrounds you. There is a full kitchen & a separate bedroom with 2 twin beds. The property also has a picnic area & places to sit, perhaps with a good book & a glass of wine while you watch the sunset. If you are a nature lover, you will enjoy the otters, seals & birdlife that we are privileged to have so close to us. During the gray whale migration times, this is a p 2183 Sherwood Drive Cambria California 93428 35.544712|-121.095444 http://www.flipkey.com/cambria-vacation-rentals/p202618/ 2012-10-01 10:52:00 2012-10-15 10:52:00 0 0 0 703 5.0 0 NULL http://images1.flipkey.com/img/photos/302459/243298/large_302459-243298-006-1346943508.jpg Beautiful Oceanfront Home in Cambria California USD 1 Ask 0 Ask Ask 4 1 http://www.flipkey.com/cambria-vacation-rentals/p202618/ Ask House Ask 0 NULL United States
4 247586 1 1 161398 Beautiful Oceanfront Home in Cambria California Located on the Central Coast of California 10 minutes from Hearst Castle.
Phone 1: Toll Free (800) 240-2277
Phone 2: (805) 927-0306 (California, USA)
direct email contact: debbie (#) maisonsdecambria.com
Leopold Cove" is a beautiful Oceanfront Home located on the Central Coast of California. It has fabulous ocean views and access to the water from a private stairway. The living area has large plate glass windows that feature 180 degree views of the Pacific Ocean. A comfortable platform style bed & a warm, cozy fireplace are also located in the living area so you can relax for hours, or even days, enjoying the beauty that surrounds you. There is a full kitchen & a separate bedroom with 2 twin beds. The property also has a picnic area & places to sit, perhaps with a good book & a glass of wine while you watch the sunset. If you are a nature lover, you will enjoy the otters, seals & birdlife that we are privileged to have so close to us. During the gray whale migration times, this is a p 2183 Sherwood Drive Cambria California 93428 35.544712|-121.095444 http://www.flipkey.com/cambria-vacation-rentals/p202618/ 2012-10-01 10:52:00 2012-10-15 10:52:00 0 0 0 703 5.0 0 NULL http://images1.flipkey.com/img/photos/302459/243298/large_302459-243298-005-1346943508.jpg Beautiful Oceanfront Home in Cambria California USD 1 Ask 0 Ask Ask 4 1 http://www.flipkey.com/cambria-vacation-rentals/p202618/ Ask House Ask 0 NULL United States
5 247586 1 1 161398 Beautiful Oceanfront Home in Cambria California Located on the Central Coast of California 10 minutes from Hearst Castle.
Phone 1: Toll Free (800) 240-2277
Phone 2: (805) 927-0306 (California, USA)
direct email contact: debbie (#) maisonsdecambria.com
Leopold Cove" is a beautiful Oceanfront Home located on the Central Coast of California. It has fabulous ocean views and access to the water from a private stairway. The living area has large plate glass windows that feature 180 degree views of the Pacific Ocean. A comfortable platform style bed & a warm, cozy fireplace are also located in the living area so you can relax for hours, or even days, enjoying the beauty that surrounds you. There is a full kitchen & a separate bedroom with 2 twin beds. The property also has a picnic area & places to sit, perhaps with a good book & a glass of wine while you watch the sunset. If you are a nature lover, you will enjoy the otters, seals & birdlife that we are privileged to have so close to us. During the gray whale migration times, this is a p 2183 Sherwood Drive Cambria California 93428 35.544712|-121.095444 http://www.flipkey.com/cambria-vacation-rentals/p202618/ 2012-10-01 10:52:00 2012-10-15 10:52:00 0 0 0 703 5.0 0 NULL http://images1.flipkey.com/img/photos/302459/243298/large_302459-243298-004-1346943508.jpg Beautiful Oceanfront Home in Cambria California USD 1 Ask 0 Ask Ask 4 1 http://www.flipkey.com/cambria-vacation-rentals/p202618/ Ask House Ask 0 NULL United States
6 247586 1 1 161398 Beautiful Oceanfront Home in Cambria California Located on the Central Coast of California 10 minutes from Hearst Castle.
Phone 1: Toll Free (800) 240-2277
Phone 2: (805) 927-0306 (California, USA)
direct email contact: debbie (#) maisonsdecambria.com
Leopold Cove" is a beautiful Oceanfront Home located on the Central Coast of California. It has fabulous ocean views and access to the water from a private stairway. The living area has large plate glass windows that feature 180 degree views of the Pacific Ocean. A comfortable platform style bed & a warm, cozy fireplace are also located in the living area so you can relax for hours, or even days, enjoying the beauty that surrounds you. There is a full kitchen & a separate bedroom with 2 twin beds. The property also has a picnic area & places to sit, perhaps with a good book & a glass of wine while you watch the sunset. If you are a nature lover, you will enjoy the otters, seals & birdlife that we are privileged to have so close to us. During the gray whale migration times, this is a p 2183 Sherwood Drive Cambria California 93428 35.544712|-121.095444 http://www.flipkey.com/cambria-vacation-rentals/p202618/ 2012-10-01 10:52:00 2012-10-15 10:52:00 0 0 0 703 5.0 0 NULL http://images1.flipkey.com/img/photos/302459/243298/large_302459-243298-003-1346943508.jpg Beautiful Oceanfront Home in Cambria California USD 1 Ask 0 Ask Ask 4 1 http://www.flipkey.com/cambria-vacation-rentals/p202618/ Ask House Ask 0 NULL United States
7 247586 1 1 161398 Beautiful Oceanfront Home in Cambria California Located on the Central Coast of California 10 minutes from Hearst Castle.
Phone 1: Toll Free (800) 240-2277
Phone 2: (805) 927-0306 (California, USA)
direct email contact: debbie (#) maisonsdecambria.com
Leopold Cove" is a beautiful Oceanfront Home located on the Central Coast of California. It has fabulous ocean views and access to the water from a private stairway. The living area has large plate glass windows that feature 180 degree views of the Pacific Ocean. A comfortable platform style bed & a warm, cozy fireplace are also located in the living area so you can relax for hours, or even days, enjoying the beauty that surrounds you. There is a full kitchen & a separate bedroom with 2 twin beds. The property also has a picnic area & places to sit, perhaps with a good book & a glass of wine while you watch the sunset. If you are a nature lover, you will enjoy the otters, seals & birdlife that we are privileged to have so close to us. During the gray whale migration times, this is a p 2183 Sherwood Drive Cambria California 93428 35.544712|-121.095444 http://www.flipkey.com/cambria-vacation-rentals/p202618/ 2012-10-01 10:52:00 2012-10-15 10:52:00 0 0 0 703 5.0 0 NULL http://images1.flipkey.com/img/photos/302459/243298/large_302459-243298-002-1346943508.jpg Beautiful Oceanfront Home in Cambria California USD 1 Ask 0 Ask Ask 4 1 http://www.flipkey.com/cambria-vacation-rentals/p202618/ Ask House Ask 0 NULL United States
8 247586 1 1 161398 Beautiful Oceanfront Home in Cambria California Located on the Central Coast of California 10 minutes from Hearst Castle.
Phone 1: Toll Free (800) 240-2277
Phone 2: (805) 927-0306 (California, USA)
direct email contact: debbie (#) maisonsdecambria.com
Leopold Cove" is a beautiful Oceanfront Home located on the Central Coast of California. It has fabulous ocean views and access to the water from a private stairway. The living area has large plate glass windows that feature 180 degree views of the Pacific Ocean. A comfortable platform style bed & a warm, cozy fireplace are also located in the living area so you can relax for hours, or even days, enjoying the beauty that surrounds you. There is a full kitchen & a separate bedroom with 2 twin beds. The property also has a picnic area & places to sit, perhaps with a good book & a glass of wine while you watch the sunset. If you are a nature lover, you will enjoy the otters, seals & birdlife that we are privileged to have so close to us. During the gray whale migration times, this is a p 2183 Sherwood Drive Cambria California 93428 35.544712|-121.095444 http://www.flipkey.com/cambria-vacation-rentals/p202618/ 2012-10-01 10:52:00 2012-10-15 10:52:00 0 0 0 703 5.0 0 NULL http://images1.flipkey.com/img/photos/302459/243298/large_302459-243298-001-1346943508.jpg Beautiful Oceanfront Home in Cambria California USD 1 Ask 0 Ask Ask 4 1 http://www.flipkey.com/cambria-vacation-rentals/p202618/ Ask House Ask 0 NULL United States
And the Omni-query I that I am constructing to replace a few hundred lines of temp tables:
SELECT DISTINCT ROW_NUMBER() OVER(ORDER BY tbl_Properties.ID DESC) AS [RowNumber], tbl_Properties.ID, tbl_Properties.UserID, tbl_Properties.CountryID, tbl_Properties.tbl_detailsID, tbl_Properties.Name,
tbl_Properties.[Description], tbl_Properties.Price, tbl_Properties.AddressLine1, tbl_Properties.AddressLine2, tbl_Properties.City, tbl_Properties.[State], tbl_Properties.Zip, tbl_Properties.AddressGPS,
tbl_Properties.[Space],
tbl_Properties.Amenities,
tbl_Properties.Policies,
tbl_Properties.URL,
tbl_Properties.DateEntered,
tbl_Properties.DateExpires,
tbl_Properties.NumViews,
tbl_Properties.IsCompanyProperty,
tbl_Properties.EnforceMinStay,
tbl_Properties.IsOtherSite,
tbl_Properties.rate_Avg,
tbl_Properties.isFeatured,
tbl_Properties.DayPrice,
tbl_Images.ImageURL,
tbl_Details.Name,
tbl_Details.check_in,
tbl_Details.check_out,
tbl_Details.currency,
tbl_Details.bathroom_count,
tbl_Details.pet,
tbl_Details.unit_size,
tbl_Details.elder,
tbl_Details.handicap,
tbl_Details.occupancy,
tbl_Details.bedroom_count,
tbl_Details.url As [LinkURL],
tbl_Details.smoking,
tbl_Details.unit_size_Units,
tbl_Details.property_Type,
tbl_Details.children,
tbl_Details.Minimum_stay,
tbl_Details.Minimum_stay_Unit,
tbl_Countries.Name As [CountryName]
FROM [tbl_Details]
INNER JOIN [tbl_Properties] ON [tbl_Details].[detailsID] = [tbl_Properties].[tbl_detailsID]
INNER JOIN [tbl_Images] ON [tbl_Images].PropertyID = [tbl_Properties].ID
INNER JOIN [tbl_Countries] ON [tbl_Countries].ID = [tbl_Properties].CountryID
The query itself is, of course, not finished yet.
If your SQLServer version supports row_number() OVER (2008,2012 support)
select * from
(select t.*,
row_number() over (partition by id order by id) as rownumber from t
) t1
where t1.rownumber=1
Here is the SQLFiddle example
Since there's no sample data you'll need to bend this response to suit your needs
select
Listings.*, SingleImage.Column1, SingleImage.Column2
from Listings
cross apply (
select top 1 *
from Images
where Listings.ListingID = Images.ListingID
) SingleImage
That needs SQL 2005 or newer (for the "cross apply" to work)
There are ways to make it work in SQL 2000 too but they're not as efficient
try this:
SELECT TOP 1 * FROM
imagestable
WHERE imagestable.landID = <theID>
This will return the first image in the table that belongs to the property.
You can INNER JOIN this query with your property table if you want to return all property info as a single record.
In SQL Server 2005+ you can use this
use tempdb
go
create table tbl (id int, s varchar(50))
insert into tbl values (1,'qwe'),(1,'asd'), (1,'qwff'),(2,'ert'),(2,'ykf'),(3,'')
;with cte
AS
(
SELECT id,s, ROW_NUMBER() OVER (PARTITION BY id ORDER BY s ) n
FROM tbl
)
SELECT id,s
FROM CTE
WHERE n=1
drop table tbl